So, I am a novice with python. I'm trying to teach myself python just to expand my skills.
I gave myself a simple challenge and I need some guidance here on how to get it done.
The goal is to read in a dhcpd leases file, read through the lease records, and end up with a list of dictionary items for each lease.
The input file will look like this:
lease 192.168.10.102 {
starts 2 2012/03/13 10:24:01;
ends 2 2012/03/20 10:24:01;
cltt 2 2012/03/13 10:24:01;
binding state active;
next binding state free;
hardware ethernet 90:4c:e5:18:5c:24;
uid "\001\220L\345\030\\$";
}
lease 192.168.10.109 {
starts 4 2012/03/15 00:44:53;
ends 4 2012/03/22 00:44:53;
cltt 4 2012/03/15 00:44:53;
binding state active;
next binding state free;
hardware ethernet 00:24:d7:2b:43:d0;
uid "\001\000$\327+C\320";
set ddns-fwd-name = "pc.domain.local.";
set ddns-txt = "3100bdf5ca9dabd07e5a8ef0ffe4755fc5";
set ddns-rev-name = "109.10.168.192.in-addr.arpa.";
client-hostname "pc";
}
lease 192.168.10.142 {
starts 4 2012/03/15 03:34:56;
ends 4 2012/03/22 03:34:56;
cltt 4 2012/03/15 03:34:56;
binding state active;
next binding state free;
hardware ethernet 00:0e:35:97:e4:30;
set ddns-rev-name = "142.10.168.192.in-addr.arpa.";
set ddns-txt = "00fc80f10784541b93c67f45b46993d112";
set ddns-fwd-name = "t42.domain.local.";
client-hostname "t42";
}
Each lease item has its set of attributes.
Now if each lease was on its own line, I'm sure I could do this using the examples from the tutorials I've been through with a line split. But I can't get my head around how to read in the block of info and then extract the items to a dictionary.
This was simple attempt:
file_to_parse = '/home/kane/djangodev/dhcpmon/sampledhcplease.txt'
file_to_write = '/home/kane/djangodev/dhcpmon/dhcpleaseoutput'
leaselist = []
filein = open(file_to_parse)
fileout = open(file_to_write,'w')
for line in filein.readlines():
current_line = line.strip()
splitline = current_line.split()
#Ignore blank lines... this is tested first before an index error on the next test
if len(splitline)== 0:
#do nothing
continue
#Ignore comments and black lines in the file
if splitline[0].startswith ('#'):
#do nothing
continue
if splitline[0].startswith ('lease'):
newlinetoadd = []
newlinetoadd.append(splitline[1:2]
Here's where I get stuck. I was going to build a list with the lease IP as 1st item, but then I realized I couldn't continue to the next line without messing up the for loop.
I'm sure I'm taking the wrong approach here. Perhaps I need to readin the whole file as a long string the split the string on the '}' character? then take each split item and split it again on the ';' character?
I'm not looking for an answer... just a push in the right direction.