【问题标题】:How do I find out if any interfaces are listening to a given IP address?如何确定是否有任何接口正在侦听给定的 IP 地址?
【发布时间】:2014-06-26 13:46:18
【问题描述】:

我正在维护一个在 RHEL 5 上运行的 bash 脚本。给定一个域名,我想确保当前机器上有一个接口监听预期的 IP 地址。

# Check that the IP is bound to this host, to avoid running on the wrong machine.
IP=$(dig +short ${EXPECTED_SUBDOMAIN}.example.com | tail -n 1)

if ! $(/sbin/ifconfig 2>/dev/null | /bin/grep -q $IP) ; then
    echo "IP for ${EXPECTED_SUBDOMAIN} ($IP) doesn't appear to be on this host"
    exit 1
fi

当 IP 地址是彼此的子字符串时,这会中断。如果我的预期 IP 地址是 1.2.3.4,如果机器的 IP 地址(甚至子网掩码!)为 11.2.3.41.2.3.40,它不会退出。

我能看到的唯一解决方案是grep "inet addr:${IP} ",但搜索其他文本似乎很脏。

是否有更可靠的方法来找出接口的 IP 地址(不会被子网掩码之类的东西弄糊涂)并进行比较?有更好的方法吗?

【问题讨论】:

  • id 说可以在 grep 模式中使用额外的文本,以确保您只匹配字符串中所需的区域。

标签: linux bash rhel5


【解决方案1】:

在你的 grep 中使用单词边界:

if ! $(/sbin/ifconfig 2>/dev/null | /bin/grep -qE "\<$IP\>" ; then
...

【讨论】:

  • 这个答案被自动标记为低质量。如果您解释了“单词边界”的工作原理,它将提供更好、更丰富的答案。
【解决方案2】:

试试这个:

 /sbin/ip addr | grep -Po 'inet \K.*?(?=(/| ))'| /bin/grep -q "^$IP$"

如果输入也被过滤,匹配字符串的开头和结尾应该可以解决您的问题。

PS。我发现 ip addr 对于虚拟 ips 比 ifconfig 更好。

【讨论】:

    猜你喜欢
    • 2011-02-19
    • 1970-01-01
    • 2013-08-19
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 2011-02-05
    相关资源
    最近更新 更多