-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_dnsmasq_conf.py
executable file
·115 lines (89 loc) · 2.68 KB
/
parse_dnsmasq_conf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#!/usr/bin/python3
# parse_dnsmasq_conf.py
# tries to parse the conf file
import argparse
import os
from pprint import pprint
import re
def parse_file(filename):
"""
for lines that start with dhcp-foo
"""
line_re = re.compile(
r"^dhcp-(?P<key>[\w\-]*)=(?P<value>.*)$")
# r"^dhcp-(?P<key>[\w\-]*)=(?P<value>.*)(?P<comment>#.*)?$")
boxes={}
for l in open(filename).read().split('\n'):
# print(l)
l = l.split('#',1)[0].strip()
lx = line_re.search(l)
if lx is not None:
kv = lx.groupdict()
# print(kv)
vs = kv['value'].split(',')
# print(vs)
if len(vs)==2:
# default line
continue
if kv['key']=='host':
boxes[vs[2]] = {
'mac': vs[0],
# 'comment':kv['comment'],
}
elif kv['key']=='option-force':
# ['tag:cnt6', '209', '"partman-auto/disk=/dev/sdb grub-installer/bootdev=/dev/sdb tasks="']
hostname = vs[0].split(':')[1]
# unpack the appends
appends = vs[2].strip('"')
# print(appends)
for append in appends.split():
# print(append)
k,v=append.split('=')
if k == "partman-auto/disk":
# partman-auto/disk=/dev/sdb
boxes[hostname]['disk'] = v
elif k == "tasks":
# tasks=ubuntu-desktop
boxes[hostname]['tasks'] = v
return boxes
def mk_yml(boxes):
"""
boxes:
- hostname:
mac:
ip:
disk:
tasks:
comment:
"""
print("boxes:")
for box in sorted(boxes):
print("- hostname: {}".format(box))
boxd = boxes[box]
for key in [
'mac', 'ip', 'disk', 'tasks', 'comment',
]:
if key in boxd:
print( " {key}: {value}".format( key=key, value=boxd[key]))
print()
def get_args():
"""
The arguments to the process are
"add", "old" or "del",
the MAC address of the host (or DUID for IPv6) ,
the IP address,
and the hostname, if known.
"""
parser = argparse.ArgumentParser(
description="""called from dnsmasq""")
parser.add_argument('--filename',
default="/etc/dnsmasq.d/macs.cfg",
help='File to save mac/hostnames (overide for testing)')
args = parser.parse_args()
return args
def main():
args = get_args()
boxes = parse_file('macs.conf')
mk_yml(boxes)
if __name__ == "__main__":
main()