Projekt

Obecné

Profil

Soubory » snmp-mac-isc-dhcp.py

Michal Kliment, 2013-10-15 12:22

 
#!/usr/bin/python -u

# This is very simple script for SNMP daemon to get MAC address from ISC DHCP leases
#
# Author: Michal Kliment <kliment@unart.cz>

import sys
from socket import inet_aton
from struct import unpack

# base OID for MAC address
base_oid = '.1.3.6.1.2.1.9999.1.1.6.4.1.8'

def parse():
leases = {}

lease_file = open("/var/lib/dhcp/dhcpd.leases", "r")

for line in lease_file:
words = line.strip().split(' ')

# first word is "lease" => start new lease info
if words[0] == 'lease':
lip = unpack("!L", inet_aton(words[1]))[0]

leases[lip] = {}
leases[lip]['ip_address'] = words[1]

# it is info about MAC address
if words[0] == 'hardware' and words[1] == 'ethernet':
leases[lip]['mac_address'] = words[2].replace(';','').replace(':',' ').upper()

config_file = open("/etc/dhcp/dhcpd.conf", "r")

host = {}

for line in config_file:
words = line.strip().split(' ')

if words[0] == 'host':
if 'ip_address' in host:
lip = unpack("!L", inet_aton(host['ip_address']))[0]

leases[lip] = host

host = {}

if words[0] == 'fixed-address':
host['ip_address'] = words[1].replace(';','')

if words[0] == 'hardware' and words[1] == 'ethernet':
host['mac_address'] = words[2].replace(';','').replace(':',' ').upper()

if 'ip_address' in host:
lip = unpack("!L", inet_aton(host['ip_address']))[0]
leases[lip] = host

return leases

leases = parse()

while True:
command = sys.stdin.readline().strip()

# empty command, quit
if command == "":
sys.exit(0)

# PING => PONG
elif command == 'PING':
sys.stdout.write("PONG\n")
sys.stdout.flush()

# snmpget
elif command == 'get':
oid = sys.stdin.readline().strip()
# get IP from oid
ip = oid.replace(base_oid, '').strip('.')

lip = unpack("!L", inet_aton(ip))[0]

leases = parse()

# always print originaly oid
print oid

if lip in leases:
print 'string'
print leases[lip]['mac_address']
else:
print ''
print ''

# snmpwalk, todo: it doesn't work :-)
elif command == 'getnext':
oid = sys.stdin.readline().strip()
# get IP from oid
ip = oid.replace(base_oid, '').strip('.')

#leases = parse()

mac = ''
getnext = False

for lip in sorted(leases.iterkeys()):
if getnext:
mac = leases[lip]['mac_address']
oid = base_oid+'.'+leases[lip]['ip_address']
getnext = (leases[lip]['ip_address'] == ip)

if mac != '':
print oid
print 'string'
print mac

else:
if oid == base_oid:
print base_oid+'.'+leases[sorted(leases.iterkeys())[0]]['ip_address']
print 'string'
print leases[sorted(leases.iterkeys())[0]]['mac_address']
else:
print ''
print 'string'
print ''
    (1-1/1)