gpt4 book ai didi

regex - 需要用一个已知的主机名grep/etc/hosts,然后从/etc/hosts中抓取该主机名的ip地址

转载 作者:太空狗 更新时间:2023-10-29 11:24:13 28 4
gpt4 key购买 nike

需要用一个已知的主机名grep/etc/hosts,然后从/etc/hosts中抓取该主机名的ip地址。

我不是程序员,不知道该怎么做。我对正则表达式的经验非常有限,但认为这可能会以某种方式起作用。我没有使用 DNS,只是使用/etc/hosts 文件进行管理。

我需要用已知主机名 grep/etc/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]

关于regex - 需要用一个已知的主机名grep/etc/hosts,然后从/etc/hosts中抓取该主机名的ip地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25277426/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com