Parsing dhcpd.leases with Python and Regex
<p>We're working on cleaning up some DHCP issues and I'm using Python and regex to parse the dhcpd.leases file. I want to write a single regex that captures each lease (see file sample at the bottom) block and then captures the IP address and MAC. My regex knowledge is rudimentary, but I think I'm on the right track. What I have so far isn't capturing everything:</p>

<p>Code so far:</p>

<pre><code>import sys, re

fp = '/Users/smitty/Dropbox/Company/Network/DHCP-Info/dhcpd.leases'
f = open(fp)
ftext = f.read()

p = re.compile(ur'(lease\s([\d]*.*).*\n.*\n.*\n.*\n.*\n.*ethernet\s(.*);*.\n.*\n.*})')

raw_record = []

parsed_record = {}

for match in re.findall(p, ftext):
    raw_record.append(match)

for record in raw_record:
    m = re.search(p, record)
    parsed_record[m.group(2)] = m.group(3)

plaintext_record = []

for ip, mac in parsed_record.iteritems():
    plaintext_record.append("IP: {0}   MAC: {1}".format(ip, mac))
</code></pre>

<p>Sample block of the dhcpd.leases file:</p>

<pre><code>lease 192.168.124.118 {
  starts 1 2014/12/01 12:42:49;
  ends 1 2014/12/01 20:42:49;
  tstp 1 2014/12/01 20:42:49;
  binding state free;
  hardware ethernet 00:0c:29:d5:ff:cb;
  uid "\001\000\014)\325\377\313";
}
lease 192.168.124.117 {
  starts 5 2015/05/01 18:49:10;
  ends 6 2015/05/02 02:49:10;
  tstp 6 2015/05/02 02:49:10;
  binding state free;
  hardware ethernet 00:0c:29:85:6f:62;
  uid "\001\000\014)\205ob";
}
lease 192.168.124.116 {
  starts 5 2015/06/05 14:48:40;
  ends 5 2015/06/05 22:48:40;
  tstp 5 2015/06/05 22:48:40;
  binding state free;
  hardware ethernet 00:0c:29:d1:3e:0d;
  uid "\001\000\014)\321&gt;\015";
}
lease 192.168.123.200 {
  starts 5 2012/07/13 11:54:46;
  ends 5 2012/07/13 11:57:42;
  tstp 5 2012/07/13 11:57:42;
  binding state free;
  hardware ethernet 88:c6:63:c6:08:52;
  uid "\001\210\306c\306\010R";
}
</code></pre>

<p>I also can't help but feel like I'm all over the place in regards to convention here (creating a list then a dict and then a list again).</p>