【问题标题】: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 地址
【发布时间】:2014-10-06 07:08:00
【问题描述】:

需要使用已知主机名 grep /etc/hosts,然后从 /etc/hosts 中捕获主机名的 IP 地址。

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

我需要使用已知主机名对 /etc/hosts 文件进行 grep,然后捕获主机条目的 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* ”,依此类推。

【问题讨论】:

  • 前两个响应似乎效果很好。我忘了提到有些机器在 /etc/hosts 文件中有多个条目。我需要使用 IP ADDRESS 字段和 HOSTNAME 字段来捕获每个条目。例如:192.168.0.1 example1.domain 192.168.0.2 example1.another.domain 192.168.100.1 example2.domain 192.168.150.5 example2.another.domain
  • 在这种情况下,请使用示例 /etc/hosts 文件更新您的问题,并更准确地了解您想要的场景输出 (a) 一个匹配 IP 的主机名和 (b) 超过一个匹配的 IP。

标签: regex linux bash dns hosts


【解决方案1】:

简单回答

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|awk 几乎总是无用的。 awk '/www.example.com/{print $1}' /etc/hosts
  • 可能想要添加$1 ~ /^#/ { next } 作为 awk 脚本的第一行以跳过任何 cmets。
  • @tripleee:哦,我知道,但是 OP 故意要求 grep。 :) 对 cme​​ts 的呼吁也很好。
【解决方案2】:

您可以使用 grepPerl regex 来输出目标主机名的 IP。

grep -oP '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?=.*hostname)' /etc/hosts

解释:

  • ^ 找到一行的开头
  • \d{1,3} 找到一到三位数字
  • \. 找到一个点
  • (?=something) 找到 something 但不将其包含在匹配项中 ("zero-width positive look-ahead assertion")
  • . 前面没有反斜杠会找到任何字符
  • * 重复前面的表达式(在本例中为“任何字符”)零次或多次

换句话说,这将找到一系列由点分隔的 1 到 3 位数字,如果它们后面跟着任何字符串,然后是 hostname,则打印它们 (grep -o),全部在这个上一行。

【讨论】:

  • +1 用于使用-o 和积极的前瞻性。我建议-m 1 限制在第一场比赛。另外,请注意,这不适用于可能位于/etc/hosts 中的 IPv6 地址(尽管 OP 没有声明他需要 v6)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2018-09-22
相关资源
最近更新 更多