1

我需要使用 cron 和 bash 来检查 IP 111.222.333.444 对于主机 sub.domain.com 是否仍然有效。

我曾尝试使用 -Pzo 进行grep,但没有成功。我不想安装pcregrep

#!/bin/bash

ipaddressused=$1

#Run a dig for sub.domain.com:

ipaddresscurrent='dig +short sub.domain.com'

echo "$ipaddresscurrent" | grep -Pzo "$ipaddressused" && echo "found" && exit 0 || echo "not found" && exit 1

ipaddresscurrent返回多个 IP,每行一个。

我该如何进行这项工作?

4

1 回答 1

2

这还不够吗?

#!/bin/bash

ipaddressused=$1

if grep -q -P "$ipaddressused" < <(dig +short sub.domain.com); then
    echo "found"
    exit 0
else
    echo "not found"
    exit 1
fi

你的脚本有什么问题?

  • 线

    ipaddresscurrent='dig +short sub.domain.com'
    

    将字符串分配给dig +short sub.domain.com变量ipaddresscurrent。相反,您可能想将commandipaddresscurrent输出分配给变量。这可以使用旧的和已弃用的反引号来完成: dig +short sub.domain.com

    ipaddresscurrent=`dig +short sub.domain.com`
    

    (但请永远不要使用反引号!)或更现代、强大和可嵌套$(...)的:

    ipaddresscurrent=$(dig +short sub.domain.com)
    
  • grep -Pzo并没有真正做到你所期望的。相反,您想安静地运行grep 因此-q标志)并检查其输出,因此以下内容将是有效的:

    echo "$ipaddresscurrent" | grep -q -P "$ipaddressused" && echo "found" && exit 0 || echo "not found" && exit 1
    

由于您并不真正需要该变量ipaddresscurrent,因此我更喜欢使用进程替换来提供grep

此外,不要使用长链&& || &&'s,它很难阅读,并且可能会产生一些微妙的副作用。

如果你想坚持你的变量,你需要一个这里的字符串

#!/bin/bash

ipaddressused=$1
ipaddresscurrent=$(dig +short sub.domain.com)

if grep -q -P "$ipaddressused" <<< "$ipaddresscurrent"; then
    echo "found"
    exit 0
else
    echo "not found"
    exit 1
fi

正如您在评论中指出的那样:

应该注意的是,如果提供的 $ipaddressused 是 111.222.333.4 并且 111.222.333.456 出现在列表中,那么也会发生匹配。这可能会导致问题。

我实际上并不知道这是否是一个请求的功能(因为脚本的参数是一个正则表达式,这实际上就是我留下-P标志的原因)。如果你真的想完全匹配一个 IP,你可以这样做:

#!/bin/bash

if grep -q "^${1//./\.}$" < <(dig +short sub.domain.com); then
    echo "found"
    exit 0
else
    echo "not found"
    exit 1
fi

假设dig使用这种方式将每行只输出一个 ip。

于 2013-07-02T18:20:01.583 回答