bash 为字符串运行 ssh 远程命令和 grep

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25357163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:10:21  来源:igfitidea点击:

Running ssh remote command and grep for a string

bashshellsshgrep

提问by Eazy

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 远程命令的脚本。我所需要的只是为某些特殊字符串 grep 执行命令的输出,这将意味着该命令已成功执行。例如,当我运行这个:

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?

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

采纳答案by konsolebox

Add grepand check exit status:

添加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

You may also place grepoutside.

你也可以放在grep外面。

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 caseor with [[ ]]:

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

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.

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

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

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

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