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

时间:2014-08-18 06:01:47

标签: bash shell ssh grep

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

ssh user@host "sudo /etc/init.d/haproxy stop"

我得到输出:

Stopping haproxy: [  OK  ]

我只需要找到“OK”字符串以确保命令执行成功。我怎么能这样做?

1 个答案:

答案 0 :(得分: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

您也可以将grep放在外面。

ssh user@host "sudo /etc/init.d/haproxy stop" | grep -Fq '[  OK  ]'

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

command && { echo "Command ran successfully."; }
command || { echo "Command failed."; }
if command; then echo "Command ran successfully."; else echo "Command failed."; fi

您还可以捕获输出并将其与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

您可以直接将$(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