【发布时间】:2026-01-19 22:50:02
【问题描述】:
我正在尝试匹配 SSH 命令的输出,但由于某种原因它无法正常工作。我正在使用 authorized_keys 将登录限制为一个命令 - 这是一个带有参数的包装脚本。
这是我的代码:
for i in `seq 2 254`; do
myoutput=$( ssh system@server01 ip 192.168.0.$i )
echo "$myoutput"
echo "$myoutput" | grep -q "not found"
if [ $? -eq 0 ]; then
echo 192.168.0.$i
exit
fi
done
这是脚本的输出:
192.168.0.2 not found in DB. Try searching live (--forcelive)
192.168.0.3 not found in DB. Try searching live (--forcelive)
192.168.0.4 not found in DB. Try searching live (--forcelive)
这应该在第一个实例中停止并回显 IP,但它会继续进行,因为所有 grep 都返回 1 而不是 0。SSH 命令本身(没有 grep)每次都返回 0。
为什么 grep 的响应编码错误?有没有更好的方法来完成我想做的事情?
【问题讨论】:
-
#1。您错过了代码末尾的
done。 #2,请缩进for循环。 #3,不要使用return作为变量名,因为它明显与shell内置冲突。 -
#4 而不是
if [ $? -eq 0 ]; then尝试做if echo "$return" | grep -q "not found"; then或更好if grep -q <<< "$return"; then -
if检查命令的返回值。只是我们太习惯于看到test命令 ([) 或内置的 shell[[,以至于我们忘记了任何返回码都可以。 -
这个内容很可能在 stderr 上,而不是在 stdout 上。
-
顺便说一句,你知道你使用的
ip命令的退出状态是否会根据它是否找到东西而变化吗?通常,检查命令的退出状态比尝试解释其输出要好得多。