【问题标题】:While loop to execute nagios commands not working properly执行nagios命令的while循环无法正常工作
【发布时间】:2017-01-24 17:33:48
【问题描述】:

我在这篇文章中写了一个小 bash 脚本:How to search for a string in a text file and perform a specific action based on the result

我注意到,当我运行脚本并检查日志时,一切似乎都在工作,但是当我查看 Nagios UI 时,我的文本文件中列出的几乎一半的服务器没有禁用它们的通知。脚本的修改版本如下:

host=/Users/bob/wsus.txt

password="P@assw0rd123"

while read -r host; do
    region=$(echo "$host" | cut -f1 -d-)

    if [[ $region == *sea1* ]]
        then
            echo "Disabling host notifications for: $host"
            curl -vs -o /dev/null -d "cmd_mod=2&cmd_typ=25&host=$host&btnSubmit=Commit" https://nagios.$region.blah.com/nagios/cgi-bin/cmd.cgi" -u "bob:$password" -k 2>&1
        else
            echo "Disabling host notifications for: $host"
            curl -vs -o /dev/null -d "cmd_mod=2&cmd_typ=25&host=$host&btnSubmit=Commit" https://nagios.$region.blah02.com/nagios/cgi-bin/cmd.cgi" -u "bob:$password" -k 2>&1
    fi
done < wsus.txt >> /Users/bob/disable.log 2>&1

如果我手动对有问题的服务器运行命令,它会在 Nagios UI 中被禁用,所以我有点困惑。仅供参考,我也不太精通 Bash,所以这是我尝试将这个过程自动化一点的尝试。

【问题讨论】:

  • 您能否从日志中确定问题是由“while”循环未读取丢失服务器的行引起的,还是因为调用了命令但失败了?
  • 将主机变量重命名为hostsfile=/Users/bob/wsus.txt,确保该文件存在,然后将完成的行更改为done &lt; $hostsfile &gt;&gt; /Users/bob/disable.log 2&gt;&amp;1。应该这样做。
  • @NagiosSupport 成功了,谢谢!我还注意到之前的一些“故障”服务器在我的文本文件中具有错误的 FQDN...

标签: bash while-loop nagios


【解决方案1】:

1 - 在第一次 https 出现之前缺少双引号:

你有:

curl -vs -o /dev/null -d "cmd_mod=2&cmd_typ=25&host=$host&btnSubmit=Commit" https://nagios.$region.blah.com/nagios/cgi-bin/cmd.cgi" -u "bob:$password" -k 2>&1

应该是:

curl -vs -o /dev/null -d "cmd_mod=2&cmd_typ=25&host=$host&btnSubmit=Commit" "https://nagios.$region.blah.com/nagios/cgi-bin/cmd.cgi" -u "bob:$password" -k 2>&1

2 - 您的第一个变量 host 从未使用过(在 while 循环内被覆盖)。 我猜你想要做的是这样的:

hosts_file="/Users/bob/wsus.txt"
log_file="/Users/bob/disable.log"

# ...

while read -r host; do
    # Do stuff with $host
done < $hosts_file >> $log_file 2>&1

3 - 我觉得这很可疑:

if [[ $region == *sea1* ]]

注意:我还没有测试过,所以这是我对此的一般感觉,可能是错误的。

$region 没有双引号,因此请确保那里没有空格/有趣的东西(但这在双括号测试 [[ 中不应该是问题)。

*sea* 看起来会被扩展以匹配与此通配符匹配的当前目录文件。如果您想将此作为正则表达式进行测试,您应该使用~= 运算符或(出于某种原因我最喜欢)grep 命令:

if grep -q ".*sea.*" <<< "$region"; then
    # Your code if match
else
    # Your code if no match
fi
  • -q 保持grep quiet
  • 不需要像[[[ 这样的测试,因为grep 的返回码已经为0,如果有任何匹配项
  • &lt;&lt;&lt; 只是将右侧字符串重定向为左侧命令的标准输入(避免像 echo "$region" | grep -q ".*sea.*" 这样的无用管道)。

如果这不能解决您的问题,请提供输入文件hosts_file 的样本以及一些输出日志。

您还可以尝试通过在脚本中加上set -xset +x 来激活调试/跟踪模式,从而了解幕后实际发生了什么。

【讨论】:

  • 谢谢,但在我做出@NagiosSupport 建议的更改后,我可以通过 Nagios Web UI 确认所有有问题的主机都没有正确响应并且通知被禁用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 2014-12-06
  • 2015-07-02
相关资源
最近更新 更多