Running ssh remote command and grep for a string

冷暖自知 提交于 2019-12-05 00:20:26

问题


I want to write script that will remotely run some ssh remote commands. All I need is to grep output of executed command for some special string which will mean that command executed successfully. For example when I run this:

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

I get output:

Stopping haproxy: [  OK  ]

All I need is to find "OK" string to ensure that command executed successfully. How can I do this?


回答1:


Add grep and check exit status:

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

You may also place grep outside.

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

Other ways to check exit status:

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

You can also capture output and compare it with case or with [[ ]]:

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

And you can embed $(exec ssh user@host "sudo /etc/init.d/haproxy stop") directly as an expression instead of passing output to a variable if wanted.

If /etc/init.d/haproxy stop sends messages to stderr instead, just redirect it to stdout so you can capture it:

sudo /etc/init.d/haproxy stop 2>&1


来源:https://stackoverflow.com/questions/25357163/running-ssh-remote-command-and-grep-for-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!