main.py
1: #!/usr/bin/python
2:
3: import DHCP.Database as database
4:
5: db = database.Database()
6:
7: db.addPattern( "mac", 'hardware\s+ethernet\s+(\S+)' )
8: db.addPattern( "ip", 'fixed-address\s+(\S+)' )
9: db.load('dhcpd.conf')
10: db.dump()
DHCP/__init__.py
1: # un fichier vide pour que python sache qu'il s'agit d'un module
DHCP/Host.py
1: #!/usr/bin/python
2:
3: class Host:
4: def __init__(self,hostname,attributes):
5: self.hostname=hostname
6: self.attributes=attributes
7:
8: def __repr__(self):
9: return 'DHCP::Host(hostname="%s",attributes=%s)'%(self.hostname,self.attributes)
DHCP/Database.py
1: #!/usr/bin/python
2: import pprint
3: import re
4: import Host
5: class Database:
6: def __init__(self):
7: self.pattern={}
8: self.hosts=[]
9: def addPattern(self,key,pattern):
10: self.pattern[key]=pattern
11: def dump(self):
12: pprint.pprint(self.hosts)
13: def load(self,filename):
14: lines=''
15: fh=open(filename)
16: for line in fh.readlines():
17: lines = lines + re.sub('#.*','',line.rstrip())
18: hosts = re.findall('host\s[^}]*}',lines)
19: for host in hosts:
20: attributes={}
21: m=re.match('host\s+(\S+)\s*{\s*(.*?)\s*}',host)
22: if m:
23: hostname,context=m.group(1),m.group(2)
24: for field in re.split(';\s*',context):
25: for key,pattern in self.pattern.iteritems():
26: m=re.search(pattern,field)
27: if m:
28: attributes[key] = m.group(1)
29: self.hosts.append(Host.Host(hostname,attributes))
stdout
1: [user@tp-anf2012 python]$ python main.py
2: [DHCP::Host(hostname="coquil-gw1",attributes={'ip': 'coquil-gw1', 'mac': '00:1d:09:0a:33:db'}),
3: DHCP::Host(hostname="fpl",attributes={'ip': 'fpl', 'mac': '00:26:b9:5d:32:32'}),
4: DHCP::Host(hostname="roundcube",attributes={'ip': 'roundcube', 'mac': '00:16:36:09:2d:b9'}),
5: DHCP::Host(hostname="deux",attributes={'ip': 'deux', 'mac': '00:14:38:63:6E:F3'}),
6: DHCP::Host(hostname="visiteur1",attributes={'mac': '00:00:aa:be:93:5d'}),
7: DHCP::Host(hostname="visiteur2",attributes={'mac': '00:60:B0:D5:3B:05'})]