Removing A Lease That Has Giving Mac From Dhcpd.leases With Python?
Solution 1:
This problem is not shaped like a regular expression nail, so please put that hammer down.
The correct tool would be to parse the contents into a python structure, filtering out the items you don't want, then writing out the remaining entries again.
pyparsing would make the parsing job easy; the following is based on an existing example:
from pyparsing import *
LBRACE,RBRACE,SEMI,QUOTE = map(Suppress,'{};"')
ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3)
hexint = Word(hexnums,exact=2)
macAddress = Combine(hexint + (':'+hexint)*5)
hdwType = Word(alphanums)
yyyymmdd = Combine((Word(nums,exact=4)|Word(nums,exact=2))+
('/'+Word(nums,exact=2))*2)
hhmmss = Combine(Word(nums,exact=2)+(':'+Word(nums,exact=2))*2)
dateRef = oneOf(list("0123456"))("weekday") + yyyymmdd("date") + \
hhmmss("time")
startsStmt = "starts" + dateRef + SEMIendsStmt="ends" + (dateRef | "never") + SEMItstpStmt="tstp" + dateRef + SEMItsfpStmt="tsfp" + dateRef + SEMIhdwStmt="hardware" + hdwType("type") + macAddress("mac") + SEMIuidStmt="uid" + QuotedString('"')("uid") + SEMIbindingStmt="binding" + Word(alphanums) + Word(alphanums) + SEMIleaseStatement= startsStmt | endsStmt | tstpStmt | tsfpStmt | hdwStmt | \
uidStmt | bindingStmtleaseDef="lease" + ipAddress("ipaddress") + LBRACE + \
Dict(ZeroOrMore(Group(leaseStatement))) + RBRACEinput= open(DHCPLEASEFILE).read()
with open(OUTPUTFILE, 'w') as output:
for lease, start, stop in leaseDef.scanString(input):
if lease.hardware.mac != mac:
output.write(input[start:stop])
The above code tersely defines the grammar of a dhcp.leases
file, then uses scanString()
to parse out each lease in the file. scanString()
returns a sequence of matches, each consisting of a parse result and the start and end positions in the original string.
The parse result has a .hardware.mac
attribute (you may want to catch AttributeError
exceptions on that, in case no hardware statement was present in the input), making it easy to test for your MAC address to remove. If the MAC address doesn't match, we write the whole lease back to an output file, using the start
and stop
positions to get the original text for that lease (much easier than formatting the lease from the parsed information).
Post a Comment for "Removing A Lease That Has Giving Mac From Dhcpd.leases With Python?"