10

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!

Community
  • 1
  • 1
alexfernandez
  • 1,938
  • 3
  • 19
  • 30
  • 2
    do you see desired hostname when you do uname -n ? in case no try executing /etc/init.d/hostname.sh – m1k3y3 Nov 24 '11 at 22:58
  • Amazing! That was it. Now `socket.gethostname()` returns the correct hostname. So the problem was just that the machine had not been rebooted and it had not taken the new hostname. If you want to answer the question with this info I will upvote it. – alexfernandez Nov 25 '11 at 08:36

4 Answers4

13

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

Nate
  • 12,499
  • 5
  • 45
  • 60
7

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].

phihag
  • 278,196
  • 72
  • 453
  • 469
7

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.

alexfernandez
  • 1,938
  • 3
  • 19
  • 30
5

Have you tried socket.gethostbyaddr(socket.gethostname())?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Emir Akaydın
  • 5,708
  • 1
  • 29
  • 57