我已经对此进行了相当多的调整,但我遇到了一个奇怪的输出流,但没有结果。基本上,我试图在我们庞大的网络上找到某些具有特定密码和处理器的 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 设备,但后 2 个应该返回肯定结果。
注意在“error”“./check.sh: line 19: [[spawn...”中,第19行是以“if [[...”开头的。
非常感谢帮助我摆脱困境的任何帮助!!
最佳答案
在 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 之外至关重要,除非您回显它。
关于linux - bash 脚本中的 expect 命令失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37401896/