运行SSH远程命令和grep一个字符串 [英] Running ssh remote command and grep for a string
问题描述
我想要写脚本,将远程运行一些SSH远程命令。所有我需要的是到grep命令执行的输出对某些特殊字符串这将意味着成功执行该命令。例如,当我运行这样的:
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"
我得到的输出:
Stopping haproxy: [ OK ]
所有我需要的是找到OK的字符串,以确保成功执行该命令。我怎样才能做到这一点?
All I need is to find "OK" string to ensure that command executed successfully. How can I do this?
推荐答案
添加的grep
,并检查退出状态:
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
您还可以将的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 [[ ]]
:
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用户@主机命令/etc/init.d/haproxy停)
直接作为一名前pression代替如果想通过输出变量。
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.
如果 /etc/init.d/haproxy停止
将消息发送到stderr而不是,只是把它重定向到stdout,所以你可以捕捉它:
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
这篇关于运行SSH远程命令和grep一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!