I am trying to get the hostname of my machine in Python. I am able to get the hostname using socket. Now I need to compare this hostname with colo list and see whether that hostname belongs to which datacenter. Either it is from dc1 or dc2 or dc3.

#!/usr/bin/python

colo = ['dc1', 'dc2', 'dc3']

hostname = socket.gethostname()

How to check whether that hostname is from which colo and then print it out that colo?

Sample Hostname will be like this -

dc1dbx1145.dc1.host.com
dc1dbx1146.dc1.host.com
dc1dbx1147.dc1.host.com
dc1dbx1148.dc1.host.com
有帮助吗?

解决方案

Split on . and test the second value:

location = hostname.split('.')[1]

Demo:

>>> hostname = 'dc1dbx1145.dc1.host.com'
>>> hostname.split('.')[1]
'dc1'

You probably want to verify that the name you found is indeed a recognized location with:

if location not in colo:
   print 'Not a recognized location'

If you don't know what part might be the location, use:

location = next((part for part in hostname.split('.') if part in colo), None)
if location is None:
    print 'Not a recognized location'

其他提示

If your hostname is consistent and always with this format, you can try something like:

data = hostname.split('.')
if len(data) == 4 and data[1] in colo:
     print "Datacenter: %s" % data[1]
else:
     print "Unknown hostname" 

The if statement is here just to avoid exception if you encountered error with the hostname fetching.

you could use the following snippet:

colo = ['dc1', 'dc2', 'dc3']
hostname = socket.gethostname()
term= hostname.split('.')[1]
print filter(lambda x: term in x,colo)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top