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 -- bryanm@widemile.com# 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 = File.open("/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      end    end  end

  f.close  return lastipend

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

0 Responses to “parsing dhcpd.leases with ruby”


  • No Comments

Leave a Reply