简体   繁体   English

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

[英]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. 在Python脚本中,我试图在Linux框中获取主机名。 It is a Debian GNU/Linux Amazon EC2 instance. 它是Debian GNU / Linux Amazon EC2实例。 I have set the correct name in /etc/hostname . 我在/etc/hostname设置了正确的名称。 The recommended solution socket.gethostname() is not working: it shows the ip- plus the IP tuple. 建议的解决方案socket.gethostname()不起作用:它显示ip-加IP元组。

I have searched on StackOverflow and nothing is coming out, eg here . 我在StackOverflow上搜索过,没有任何内容出来,例如这里 socket.getfqdn() is even worse: it yields ip-[IP tuple].eu-west-1.compute.internal . socket.getfqdn()更糟糕的是:它产生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 ? 我做错了什么,或者没有干净的解决方案来获取/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. 当然,备份解决方案是读取文件etc/hostname本身,但本质上依赖于平台的东西在某种程度上是异常的。 Thanks! 谢谢!

Try os.uname() . 尝试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()) ." 但是,正如文档本身所述,“获取主机名的更好方法是socket.gethostname()甚至socket.gethostbyaddr(socket.gethostname()) 。”

The generic source for the hostname is hostname(1) . 主机名的通用源是hostname(1) This program calls the equivalent of uname -n . 该程序调用相当于uname -n

In Python, you can either use platform.node() or os.uname()[1] . 在Python中,您可以使用platform.node()os.uname()[1]

First of all, all credit should go to m1k3y02, who gave me the hint in a comment. 首先,所有的信用都应该转到m1k3y02,他在评论中给了我一些提示。 Now, for the sake of posterity I will give the correct answer: my Amazon EC2 has not been rebooted in a long time. 现在, 为了后人,我会给出正确的答案:我的Amazon EC2在很长一段时间内没有重新启动。 I set the hostname in /etc/hostname but it did not reach the system, as evidenced by uname -n . 我在/etc/hostname设置了主机/etc/hostname但它没有到达系统, uname -n证明了这一点。 So simply running /etc/init.d/hostname.sh did the trick. 所以简单地运行/etc/init.d/hostname.sh就可以了。 After that, socket.gethostname() worked as intended. 之后, socket.gethostname()按预期工作。

The lesson here: first see if the system gets it, and only after that blame the language. 这里的教训:首先看看系统是否得到它, 只有经过责备的语言。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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