Linux 上的 Python:在 /etc/hostname 中获取主机名
我试图从 Python 脚本中获取 Linux 机器中的主机名。它是 Debian GNU/Linux Amazon EC2 实例。我已在 /etc/hostname
中设置了正确的名称。推荐的解决方案 socket.gethostname()
不起作用:它显示 ip- 加上 IP 元组。
我在 StackOverflow 上搜索过,但没有任何结果,例如 在这里。 socket.getfqdn()
更糟糕:它生成 ip-[IP tuple].eu-west-1.compute.internal
。
我是否做错了什么,或者没有干净的解决方案来获取 /etc/hostname
中的主机名?当然,备份解决方案是读取文件 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, 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
os.uname()
。根据 文档,它是返回的元组中的第二个位置。但是,正如文档本身所述,“获取主机名的更好方法是
socket.gethostname()
甚至socket.gethostbyaddr(socket.gethostname())
”。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 evensocket.gethostbyaddr(socket.gethostname())
."首先,所有的功劳都应该归功于 m1k3y02,他在评论中给了我提示。现在,为了为了子孙后代,我将给出正确的答案:我的 Amazon EC2 已经很长时间没有重新启动了时间。我在
/etc/hostname
中设置了主机名,但它没有到达系统,如uname -n
所证明的那样。因此,只需运行/etc/init.d/hostname.sh
就可以了。之后,socket.gethostname()
按预期工作。这里的教训是:首先看看系统是否得到它,然后才归咎于语言。
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 byuname -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.
主机名的通用来源是 hostname(1)。该程序调用相当于
uname -n
。在 Python 中,您可以使用
platform.node()< /code>
或
os.uname()[1]
。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()
oros.uname()[1]
.您是否尝试过
socket.gethostbyaddr(socket.gethostname())
?Have you tried
socket.gethostbyaddr(socket.gethostname())
?