Bash:查找主机名的 IP,包括搜索中的 /etc/hosts

Ale*_*ysh 18 linux dns bash ubuntu hosts-file

Ubuntu 10.10+

在我的脚本中,我需要查找给定主机名的 IP。

如果该名称在 中列出/etc/hosts,则命令应该打印来自 的 IP /etc/hosts,而不是来自 DNS 服务器。

我尝试过的命令 ( nslookup, dig, host) 完全忽略/etc/hosts- 至少对于 DNS 服务器不知道的名称。

注意:我更喜欢不需要我/etc/hosts手动grep的解决方案。

Ign*_*ams 24

getent 使用低级 glibc 信息函数来查询所有配置的源。

$ getent ahosts amd.com
163.181.249.32  STREAM amd.com
163.181.249.32  DGRAM  
163.181.249.32  RAW    
$ getent ahosts ipv6.google.com
2001:4860:b009::69 STREAM ipv6.l.google.com
2001:4860:b009::69 DGRAM  
2001:4860:b009::69 RAW    
Run Code Online (Sandbox Code Playgroud)

  • ```getent hosts amd.com``` 可能简单一点 (4认同)

l0b*_*0b0 6

$ gethostip localhost
localhost 127.0.0.1 7F000001
$ gethostip -d example.org
192.0.43.10
Run Code Online (Sandbox Code Playgroud)

syslinux包中,至少在 Ubuntu 12.04 中。