-
Notifications
You must be signed in to change notification settings - Fork 0
/
hostentriesupdate.py
executable file
·74 lines (54 loc) · 1.83 KB
/
hostentriesupdate.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
#!/usr/bin/python
from subprocess import check_output,CalledProcessError
vmscommandoutput = check_output(["virsh", "list"])
def cleanup(records):
records.pop(0)
records.pop(0)
records.pop()
records.pop()
def getvirtualmachinenames(vmlist):
listelements = vmlist.decode('ascii').split("\n")
cleanup(listelements)
vms = []
for i in listelements:
vms.append(i.strip().split()[1])
return vms
def getmacaddress(hostnames):
macs = []
for hostname in hostnames:
maccommandoutput = check_output(["virsh", "domiflist", "{}".format(hostname)])
listelements2 = maccommandoutput.decode('ascii').split("\n")
cleanup(listelements2)
mac = listelements2[0].split(" ")[-1:][0]
macs.append(mac)
return macs
def getipaddress():
ips = []
macid = []
ipcommandoutput = check_output(["virsh", "net-dhcp-leases", "default"])
listelements3 = ipcommandoutput.decode('ascii').split("\n")
cleanup(listelements3)
for i in listelements3:
x = i.split(" ")
while '' in x:
x.remove('')
macid.append(x[2]),ips.append(x[4].split("/")[0])
mactoips = dict(zip(macid,ips))
return mactoips
vms = getvirtualmachinenames(vmscommandoutput)
macids = getmacaddress(vms)
hosttomac = dict(zip(vms,macids))
mactoips = getipaddress()
hostentries = []
for i in vms:
entry = "{} {}".format(mactoips[hosttomac[i]],i)
hostentries.append(entry)
check_output(["cp", "-prv", "/root/config/hosts", "/root/config/hostsnew"])
f= open(r"/root/config/hostsnew","a+")
for i in hostentries:
f.write(i+"\n")
f.close()
check_output(["cp", "-prv", "/root/config/hostsnew", "/etc/hosts"])
for i in vms:
check_output(["scp", "-prv", "/root/config/hostsnew", "root@{}:/etc/hosts".format(i)])
print("host entries updated in {}".format(i))