Linux 上的 Python:在 /etc/hostname 中获取主机名

发布于 2024-12-18 10:15:37 字数 558 浏览 1 评论 0原文

我试图从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

疯狂的代价 2024-12-25 10:15:37

尝试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 even socket.gethostbyaddr(socket.gethostname())."

蓝海似她心 2024-12-25 10:15:37

首先,所有的功劳都应该归功于 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 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.

简美 2024-12-25 10:15:37

主机名的通用来源是 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() or os.uname()[1].

小矜持 2024-12-25 10:15:37

您是否尝试过socket.gethostbyaddr(socket.gethostname())

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文