简体   繁体   中英

Python on Linux: get host name in /etc/hostname

From within a Python script I am trying to get the host name in a Linux box. It is a Debian GNU/Linux Amazon EC2 instance. I have set the correct name in /etc/hostname . The recommended solution socket.gethostname() is not working: it shows the ip- plus the IP tuple.

I have searched on StackOverflow and nothing is coming out, eg here . socket.getfqdn() is even worse: it yields ip-[IP tuple].eu-west-1.compute.internal .

Am I doing something wrong, or is there no clean solution to get the hostname in /etc/hostname ? Of course the back-up solution is to read the file etc/hostname itself, but something so inherently platform-dependent is somehow too aberrant. Thanks!

Try os.uname() . According to the doc , it is the second position in the tuple returned.

But, as the doc itself states, the "better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()) ."

The generic source for the hostname is hostname(1) . This program calls the equivalent of uname -n .

In Python, you can either use platform.node() or os.uname()[1] .

First of all, all credit should go to m1k3y02, who gave me the hint in a comment. Now, for the sake of posterity I will give the correct answer: my Amazon EC2 has not been rebooted in a long time. I set the hostname in /etc/hostname but it did not reach the system, as evidenced by uname -n . So simply running /etc/init.d/hostname.sh did the trick. After that, socket.gethostname() worked as intended.

The lesson here: first see if the system gets it, and only after that blame the language.

你试过socket.gethostbyaddr(socket.gethostname())吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM