Scanning DHCP Leases
This morning I added a machine to my network that I knew used DHCP and when it had booted I wanted to know what IP address it had been given. I run the ISC DHCP server so though it would be nice to have a script that would query the leases file (dhcpd.leases) and show all current leases. So, I wrote this script and thought I'd submit it as my first script here. Figure it might be useful if someone gets local file inclusion or some other way of nabbing the file off a server.
#!/usr/bin/env ruby
require "time"
f = File.new("dhcpd.leases", "r")
# init
ip = nil
end_date = nil
mac = nil
while (line = f.gets)
line.strip!
if /^lease ((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)) \{/.match line
ip = $1
end
if /ends [0-9]* ([^;]*);/.match line
begin
end_date = Time.parse($1)
if (end_date <= Time.now)
end_date = nil
ip = nil
end
rescue
end
end
if /hardware ethernet ([0-9a-f:]{17});/i.match line
mac = $1
end
if line == "}" && !ip.nil? && !end_date.nil?
print "Address: " + ip + " Valid till: " + end_date.strftime("%Y-%m-%d %H:%M:%S")
if !mac.nil?
print " MAC: " + mac
end
print "\n"
# reset
ip = nil
end_date = nil
mac = nil
end
end
PS, I actually found the machine by an nmap ping scan and looking at the OUI field but was thinking of this script while I was running it