如何在文本文件中搜索字符串并根据结果执行特定操作

时间:2016-12-30 22:45:57

标签: bash

我对Bash的经验很少,但这就是我想要完成的事情。

我有两个不同的文本文件,其中包含一堆服务器名称。在安装任何Windows更新并重新启动它们之前,我需要禁用所有nagios主机/服务警报。

host=/Users/bob/WSUS/wsus_test.txt
password="my_password"

while read -r host
do
  curl -vs -o /dev/null -d "cmd_mod=2&cmd_typ=25&host=$host&btnSubmit=Commit" "https://nagios.fqdn.here/nagios/cgi-bin/cmd.cgi" -u "bob:$password" -k
done < wsus_test.txt >> /Users/bob/WSUS/diable_test.log 2>&1

这是我当前代码的缩减形式,按预期工作,但是,我们在一堆区域中有服务器。每个服务器名称前面都有一个基于区域的3字母代码(即LAX,NYC等)。其次,我们在每个区域都有一个nagios服务器,所以我需要上面的代码根据传入的服务器名称连接到正确的区域nagios服务器。

我尝试将4个测试服务器添加到文本文件中,只需添加如下所示的行:

    if grep lax1 /Users/bob/WSUS/wsus_text.txt; then
      <same command as above but with the regional nagios server name>
    fi

这没有按预期工作,实际上没有通过API调用禁用/启用任何内容。再说一遍,我对Bash做的很少,所以任何指针都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

从主机名中提取区域并在Nagios URL中使用它,如下所示:

while read -r host; do
  region=$(cut -f1 -d- <<< "$host")
  curl -vs -o /dev/null -d "cmd_mod=2&cmd_typ=25&host=$host&btnSubmit=Commit" "https://nagios-$region.fqdn.here/nagios/cgi-bin/cmd.cgi" -u "bob:$password" -k
done < wsus_test.txt >> /Users/bob/WSUS/diable_test.log 2>&1