linux-python生成主机唯一UUID

主机需要有一个唯一的uuid,对于物理机存在主板uuid获取不到的情况,所以根据相关信息,生成一个

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
#!/usr/bin/env python
#coding: utf-8
import re
import subprocess

'''
兼容python2/python3
'''
#默认shell执行函数
def shellutil(cmd):
p = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
return p.communicate()
#获取厂商信息
def getManufacturer():
cmd="dmidecode -t 1|grep Manufacturer|awk -F': ' '{print $2}'"
resp=shellutil(cmd)
if resp[1] == "":
return resp[0].decode('UTF-8').lower().zfill(4)
else:
return "null"
#获取主板sn
def getSN():
cmd="dmidecode -t 1|grep 'Serial Number'|awk '{print $NF}'"
resp = shellutil(cmd)
if resp[1] == "":
return resp[0].decode('UTF-8').lower()[0:4].zfill(4)
else:
return "0000"
#获取设备UUID
def getUUID():
cmd="dmidecode -s system-uuid"
resp = shellutil(cmd)
uuid = resp[0].decode('UTF-8')
match = re.match(r'(.*?)-(.*?)-(.*?)-(.*?)-(.*?)', uuid, re.M | re.I)
if resp[1] == "" and match:
return resp[0].strip()
else:
return "ERROR"
#获取默认路由网卡mac
def getFirstIpMac():
resp=[]
eth_cmd="ip route|grep default|awk '{print $NF}'"
eth_resp = shellutil(eth_cmd)
if eth_resp[1] == "":
resp.insert(0,eth_resp[0].strip().decode('UTF-8').lower().zfill(4))
else:
resp.insert(0,"lo".lower().zfill(4))
mac_cmd='ifconfig eth2|egrep ":[0-9a-z]*:"|awk \'{print $2}\''
mac_resp=shellutil(mac_cmd)
if mac_resp[1] == "":
resp.insert(1,mac_resp[0].decode('UTF-8').replace(":","")[4:])
else:
resp.insert(1,"00000000")
return resp
def main():
uuid_err_pre = "00000000"
uuid=getUUID()
route_eth= getFirstIpMac()[0]
route_eth_mac=getFirstIpMac()[1]
if uuid != "ERROR":
print(uuid)
else:
fact=getManufacturer()[0:4]
print('{}-{}-{}-{}-{}'.format(uuid_err_pre,fact,getSN(),route_eth,route_eth_mac))
if __name__ == '__main__':
main()