00001
00002
00003 def hostid():
00004 '''Return the hostid. Rely on system's hostid executable or,
00005 failing that, try to construct one from the IP associated with the
00006 hostname. Both rely on a correctly setup /etc/hosts file'''
00007
00008 import os
00009 hid = 0
00010 try:
00011 hid = os.popen("hostid").read().strip()
00012 hid = int("0x"+hid,16)
00013 except Exception,err:
00014 print 'Warning, failed to get hostid directly, error message was `',str(err),'` now try to get hostid from hostname.'
00015 hid = 0
00016 pass
00017
00018 if 0 == hid:
00019 import socket
00020 hn = socket.gethostname()
00021 try:
00022 ip = socket.gethostbyname(hn)
00023 except socket.error, err:
00024 print 'Warning, failed to get hostid, will use 0. Error message:\n',str(err)
00025 return 0
00026 l = map(lambda x: int(x),ip.split("."))
00027 l = [l[1], l[0],l[3],l[2]]
00028 for x in l:
00029 hid = (hid<<8) + x
00030 pass
00031
00032 return hid
00033
00034 if '__main__' == __name__:
00035 print hostid()
00036
00037