Created
March 28, 2012 14:47
-
-
Save flagranterror/2226791 to your computer and use it in GitHub Desktop.
ISC DHCPD lease parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cache_leases | |
leases = {} | |
File.open('/path/to/dhcpd.leases', 'r').read.gsub(/\n/, '').split(/}/).each do |lease| | |
l = lease.split(';') | |
if l.index(' next binding state free') | |
l[0].gsub!(/.*lease (.*?) {.*/, '\1') | |
leases[l[0]] = l if l[0] =~ /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/ | |
end | |
end | |
return leases | |
end | |
def mac_from_ip(ip) | |
found = false | |
leases = cache_leases | |
if leases[ip] | |
found = true | |
@mac = leases[ip].grep(/hardware ethernet/)[0].gsub(/.*hardware ethernet (.*)/, '\1') | |
end | |
return found ? @mac : "MAC address not found!" | |
end | |
def ip_from_mac(mac) | |
found = false | |
leases = cache_leases | |
leases.each do |id,d| | |
if d.include?(" hardware ethernet #{mac}") | |
found = true | |
@ip = id | |
end | |
end | |
return found ? @ip : "IP address not found" | |
end | |
def count_leases | |
leases = cache_leases | |
return leases.count.to_s | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'sinatra' | |
require '/path/to/lease_parser.rb' | |
get '/ip_from_mac/:mac_address' do | |
mac = params[:mac_address].gsub(/%3A/, ':') | |
if mac =~ /[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}/ | |
ip_from_mac(mac) | |
else | |
"NO - #{mac} invalid" | |
end | |
end | |
get '/mac_from_ip/:ip_address' do | |
if params[:ip_address] =~ /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/ | |
mac_from_ip(params[:ip_address]) | |
else | |
"NO - #{ip} invalid" | |
end | |
end | |
get '/count_leases/' do | |
count_leases | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment