Since I wrote my original pyparsing post a few days ago, I've done some more work on refining my ISC dhcpd.conf host parsing example program. I also received some useful comments and suggests from Paul McGuire, the author the pyparsing module (thanks, Paul!), which I have also tried to incorporate.
It's it's currently just a useless toy program but it is starting to look quite pretty.
The output is still the same as that of the original program.
If you want it to read your sample data from a file, just change the following line:
... to:
It's it's currently just a useless toy program but it is starting to look quite pretty.
#!/usr/bin/python
from pyparsing import *
# An few host entries from dhcpd.conf
sample_data = """
# A host with dynamic DNS attributes
host a.foo.bar {
ddns-hostname a;
ddns-domainname "foo.bar";
hardware ethernet 00:11:22:33:44:55;
fixed-address 192.168.100.10, 192.168.200.50;
}
# A simple multi-line host
host b.foo.bar {
hardware ethernet 00:0f:12:34:56:78;
fixed-address 192.168.100.20;
}
# A simple single-line host
host c.foo.bar { hardware ethernet 00:0e:12:34:50:70; fixed-address 192.168.100.40; }
"""
digits = "0123456789"
colon,semi,period,comma,lbrace,rbrace,quote = map(Literal,':;.,{}"')
number = Word(digits)
hexint = Word(hexnums,exact=2)
dnschars = Word(alphanums + '-') # characters permissible in DNS names
mac = Combine(hexint + (":" + hexint) * 5)("mac_address")
ip = Combine(number + period + number + period + number + period + number)
ips = delimitedList(ip)("ip_addresses")
hardware_ethernet = Literal('hardware') + Literal('ethernet') + mac + semi
hostname = dnschars
domainname = dnschars + OneOrMore("." + dnschars)
fqdn = Combine(hostname + period + domainname)("fqdn")
fixed_address = Literal('fixed-address') + ips + semi
ddns_hostname = Literal('ddns-hostname') + hostname + semi
ddns_domainname = Literal('ddns-domainname') + quote + domainname + quote + semi
# Put the grammar together to define a host declaration
host = Literal('host') + fqdn + lbrace + Optional(ddns_hostname) + Optional(ddns_domainname) + Optional(hardware_ethernet) + Optional(fixed_address) + rbrace
results = host.scanString(sample_data)
for result in results:
print result[0].fqdn, result[0].mac_address , result[0].ip_addresses
file.close()
The output is still the same as that of the original program.
If you want it to read your sample data from a file, just change the following line:
results = host.scanString(sample_data)
... to:
filename = "/etc/dhcp3/dhcpd.conf"
file = open(filename, "rb")
results = host.scanString("".join(file.readlines()))
Comments