bash 脚本中的 expect 命令失败

expect command in bash script failing

我已经对此进行了相当多的调整,但我遇到了一个奇怪的输出流,但没有结果。基本上,我试图在我们庞大的网络上找到某些具有特定密码和处理器的 ssh 设备。这是脚本:

#/bin/bash
for i in 54
do
  for j in 1 13 14 15
  do
    out=$(expect -c "spawn /usr/bin/ssh some_guy@10.2.$i.$j cat /proc/cpuinfo | grep MyString
      expect {
        -re \".*Are.*.*yes.*no.*\" {
        send \"yes\n\"
        exp_continue
        }

        \"*?assword:*\" {
        send \"mypasswd\"
        send \"\n\"
        exp_continue
        }
      }")
    if [["$out" != ""]]
    then
      echo "10.2.$i.$j" >> rpiout.txt
    fi
  done
done

ssh 命令本身可以正常工作。此外,期望脚本工作正常。此外,如果我在 "if [[...]]" 语句之前插入一个 "echo $out",我会从 SSH 命令获得预期的输出。但是,尝试写入文件时,我将此输出输出到命令行并且没有日志文件...:

./check.sh: line 19: [[spawn /usr/bin/ssh some_guy:@10.2.54.1 cat /proc/cpuinfo | grep MyString
some_guy:@10.2.54.1's password:
Permission denied, please try again.
some_guy:@10.2.54.1's password:
Permission denied, please try again.
some_guy:@10.2.54.1's password:
: No such file or directoryy,password).
./check.sh: line 19: [[spawn /usr/bin/ssh some_guy:@10.2.54.13 cat /proc/cpuinfo | grep MyString
some_guy:@10.2.54.13's password:
: No such file or directory
./check.sh: line 19: [[spawn /usr/bin/ssh some_guy:@10.2.54.14 cat /proc/cpuinfo | grep MyString
some_guy:@10.2.54.14's password:
: No such file or directory
: No such file or directoryawn /usr/bin/ssh some_guy:@10.2.54.15 cat /proc/cpuinfo | grep MyString

第一个要求密码3次的是正确的(因为它不是目标设备之一)。第二个 2 是不存在的 IP 设备,但最后两个应该 return 一个肯定的结果。

请注意,在 "error" "./check.sh: line 19: [[spawn...] 中,第 19 行是以 "if [[...".

非常感谢任何帮助我摆脱困境的人!!

in bash [[ 不仅仅是语法,它是一个命令。与任何其他命令一样,它需要空格将其与其参数分开。

没有

if [["$out" != ""]]

但是

if [[ "$out" != "" ]]

if [[ -n "$out" ]]

此外,由于 expect 回显命令的方式就像您在终端看到的那样,输出不太可能 永远 为空。尝试这样的事情:

out=$( expect <<END
    spawn -noecho /usr/bin/ssh some_guy@10.2.$i.$j sh -c {grep -q MyString /proc/cpuinfo || echo _NOT_FOUND_}
    expect {
        -re ".*Are.*.*yes.*no.*" {
            send "yes\r"
            exp_continue
        }
        "*?assword:*" {
            send "mypasswd\r"
            exp_continue
        }
        eof
    }
END
)

if [[ $out == *_NOT_FOUND_* ]]; then
    echo "MyString not found on host 10.2.$i.$j"
fi

其中 _NOT_FOUND_ 是一些您在 /proc/cpuinfo

中看不到的字符串

这里的 -noecho 是至关重要的,它可以将“_NOT_FOUND_”排除在 $out 之外,除非您回显它。