运行ssh remote命令和grep查找字符串

Eld*_*dar 5 ssh bash shell grep

我想编写远程运行一些ssh远程命令的脚本.我需要的是为一些特殊的字符串grep输出执行的命令,这意味着命令执行成功.例如,当我运行这个:

ssh user@host "sudo /etc/init.d/haproxy stop"
Run Code Online (Sandbox Code Playgroud)

我得到输出:

Stopping haproxy: [  OK  ]
Run Code Online (Sandbox Code Playgroud)

我只需要找到"OK"字符串以确保命令执行成功.我怎样才能做到这一点?

kon*_*box 5

添加grep并检查退出状态:

ssh user@host "sudo /etc/init.d/haproxy stop | grep -Fq '[  OK  ]'"
if [ "$#" -eq 0 ]; then
    echo "Command ran successfully."
else
    echo "Command failed."
fi
Run Code Online (Sandbox Code Playgroud)

你也可以放在grep外面.

ssh user@host "sudo /etc/init.d/haproxy stop" | grep -Fq '[  OK  ]'
Run Code Online (Sandbox Code Playgroud)

检查退出状态的其他方法:

command && { echo "Command ran successfully."; }
command || { echo "Command failed."; }
if command; then echo "Command ran successfully."; else echo "Command failed."; fi
Run Code Online (Sandbox Code Playgroud)

您还可以捕获输出,并与比较case[[ ]]:

OUTPUT=$(exec ssh user@host "sudo /etc/init.d/haproxy stop")
case "$OUTPUT" in
*'[  OK  ]'*)
    echo "Command ran successfully."
    ;;
*)
    echo "Command failed."
esac

if [[ $OUTPUT == *'[  OK  ]'* ]]; then
    echo "Command ran successfully."
else
    echo "Command failed."
fi
Run Code Online (Sandbox Code Playgroud)

并且您可以$(exec ssh user@host "sudo /etc/init.d/haproxy stop")直接嵌入表达式,而不是将输出传递给变量(如果需要).

如果/etc/init.d/haproxy stop将消息发送到stderr,只需将其重定向到stdout即可捕获它:

sudo /etc/init.d/haproxy stop 2>&1
Run Code Online (Sandbox Code Playgroud)