[英]Need to grep /etc/hosts with a known hostname, and then capture the ip address for the hostname from /etc/hosts
需要使用已知主机名grep / etc / hosts,然后从/ etc / hosts捕获主机名的ip地址。
我不是程序员,也不知道怎么做。 我对正则表达式的经验非常有限,但认为这可能会以某种方式起作用。 我没有使用DNS,只使用/ etc / hosts文件进行管理。
我需要使用已知的主机名grep / etc / hosts文件,然后捕获hosts条目的IP地址。 主机文件是标准格式:
请帮忙!
#
维护网络
192.168.80.192 testsrv01-maint
192.168.80.193 testsrv02-maint
192.168.80.194 testsrv03-maint
#
熄灯网络
192.168.120.192 testsrv01-ilo
192.168.120.193 testsrv02-ilo
192.168.120.194 testsrv03-ilo
#
主要数据网络
192.168.150.192 testsrv01-pri
192.168.150.193 testsrv02-pri
192.168.150.194 testsrv03-pri
#
次要数据网
192.168.200.192 testsrv01-sec
192.168.200.193 testsrv02-sec
192.168.200.194 testsrv03-sec
我需要能够将每台机器的ip地址和完整主机名条目捕获到我可以使用的变量中。 例如,运行文件寻找匹配“testsrv01 *”,并捕获该搜索的所有IP地址和名称。 然后同样为“testsrv02 *”,依此类推。
简单回答
ip=$(grep 'www.example.com' /etc/hosts | awk '{print $1}')
更好的答案简单的答案返回所有匹配的IP,甚至是评论行上的IP。 您可能只想要第一个非评论匹配,在这种情况下只需使用awk:
ip=$(awk '/^[[:space:]]*($|#)/{next} /www.example.com/{print $1; exit}' /etc/hosts)
另一件事如果你在某个时候关心解决www.example.com你的系统是否配置为使用主机,dns等,那么考虑一下鲜为人知的getent
命令:
ip=$(getent hosts 'www.example.com' | awk '{print $1}')
编辑以响应更新
$ cat script.sh
#!/bin/bash
host_to_find=${1:?"Please tell me what host you want to find"}
while read ip host; do
echo "IP=[$ip] and host=[$host]"
done < <(awk "/^[[:space:]]*($|#)/{next} /$host_to_find/{print \$1 \" \" \$2}" /etc/hosts)
$ ./script.sh testsrv01
IP=[192.168.80.192] and host=[testsrv01-maint]
IP=[192.168.120.192] and host=[testsrv01-ilo]
IP=[192.168.150.192] and host=[testsrv01-pri]
IP=[192.168.200.192] and host=[testsrv01-sec]
您可以将grep
与Perl正则表达式一起使用,以输出目标主机名的IP。
grep -oP '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?=.*hostname)' /etc/hosts
说明:
^
找到一行的开头 \\d{1,3}
找到一到三位数字 \\.
找到一个点 (?=something)
找到了something
但是在匹配中没有包含它(“ 零宽度正向前瞻断言 ”) .
没有前面的反斜杠可以找到任何字符 *
重复前面的表达式(在这种情况下为“任何字符”)零次或多次 换句话说,这将找到一系列由点分隔的四位一位到三位数字,如果它们后跟任何字符串然后是hostname
,则打印它们( grep -o
),所有这些都在一行上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.