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
Running ssh remote command and grep for a string
提问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 grep
and 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 grep
outside.
你也可以放在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 case
or 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 stop
sends 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