forked from FredHutch/proxmox-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxhostname.py
executable file
·80 lines (66 loc) · 2.38 KB
/
proxhostname.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
#! /usr/bin/env python3
# setting the proxmox VM hostname according to proxmox config
import sys, os, json, fileinput, socket, warnings
#from proxmoxer import ProxmoxAPI
with warnings.catch_warnings():
warnings.filterwarnings("ignore",category=DeprecationWarning)
import pyproxmox
PROXHOST='proxmox.fhcrc.org'
def getmac(interface):
try:
mac = open('/sys/class/net/'+interface+'/address').readline().upper()
except:
mac = "00:00:00:00:00:00"
return mac[0:17]
def getmacs():
macs = []
nics = os.listdir('/sys/class/net/')
for n in nics:
macs.append(getmac(n))
return macs
def getScriptPath():
return os.path.dirname(os.path.realpath(sys.argv[0]))
try:
user, pwd = open(getScriptPath()+'/creds').readline().strip().split("|")
except:
print('Could not open creds file %s.' % getScriptPath()+'/creds')
print('Format of creds file: username@DOMAIN|password (all in one line)')
sys.exit()
#proxmox = ProxmoxAPI(PROXHOST, user=user, password=pwd, verify_ssl=False)
hostname=socket.gethostname()
newhost=hostname
a = pyproxmox.prox_auth(PROXHOST, user, pwd,False)
p = pyproxmox.pyproxmox(a)
mymacs = getmacs()
nodes = []
nodelist=p.getNodes()['data']
for n in nodelist:
nodes.append(n['node'])
for node in nodes:
vms = p.getNodeVirtualIndex(node)['data']
for v in vms:
j = p.getVirtualConfig(node,v['vmid'])
mac=j['data']['net0'].split('=')[1].split(',')[0]
if mac.upper() in mymacs:
print('%s: %s' % (v['name'], mac))
newhost=v['name'].lower()
vms = p.getNodeContainerIndex(node)['data']
for v in vms:
j = p.getContainerConfig(node,v['vmid'])
mac=j['data']['netif'].split(',')[1].split('=')[1]
if mac.upper() in mymacs:
print('%s: %s' % (v['name'], mac))
newhost=v['name'].lower()
if newhost != hostname:
with fileinput.FileInput('/etc/hosts', inplace=True, backup='.bak') as file:
for line in file:
print(line.replace("127.0.0.1 %s" % hostname, "127.0.0.1 %s" % newhost), end='')
f = open('/etc/hostname','w')
f.write(newhost+'\n')
f.close()
os.system('hostname %s' % newhost)
os.system('dhclient -r')
os.system('dhclient')
print ('changed hostname to %s' % newhost)
else:
print ('hostname for this MAC is in line with proxmox db or MAC not found in proxmox.')