Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

linux

ip

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, e.g. 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!

like image 235
alexfernandez Avatar asked Nov 24 '11 22:11

alexfernandez


People also ask

How do I find my host name in Python?

In order to get the hostname of a computer, you can use socket and its gethostname() functionality. The gethostname() return a string containing the hostname of the machine where the Python interpreter is currently executing.

How do I find my IP in Python?

Use the socket. getsockname() Funtion to Get the Local IP Address in Python. If the computer device has a route connected to the Internet, then we can use the getsockname() function. It returns the IP address and port in the form of a tuple.

What is a hostname example?

On the Internet, a hostname is a domain name assigned to a host computer. For example, if Computer Hope had two computers on its network named "bart" and "homer," the domain name "bart.computerhope.com" is connecting to the "bart" computer.


2 Answers

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.

like image 113
alexfernandez Avatar answered Oct 25 '22 04:10

alexfernandez


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())."

like image 39
Nate Avatar answered Oct 25 '22 05:10

Nate