parsing dhcpd.leases with ruby

Needed to get the IP address of a certain mac from the dhcpd leases file, wrote this, seems to work, albeit short. IANAP, YMMV. All of my programming comes from looking at examples, so any faults of mine are actually someone else’s. Blame fR and niblr!

#!/usr/bin/ruby -w
# getdhcpip.rb Bryan McLellan --
# parse through dhcpd.leases in search of a mac to get it's current ip
# assume not malformed. remember that this is a log file and the most recent (bottom) is the most accurate

def lastdhcpip(ourmac)
curLeaseIp = nil
curLeaseMac = nil
lastip = nil

f ="/var/lib/dhcp/dhcpd.leases")
f.each do |line|
case line
when /lease (.*) \{/
curLeaseIp = $1
when /hardware ethernet (.*);/
curLeaseMac = $1
if ourmac == curLeaseMac
lastip = curLeaseIp

return lastip

if ARGV[0]
puts lastdhcpip(ARGV[0])
puts "Requires MAC address as argument: getdhcpip.rb 00:00:00:00:00:00"

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.