shell 脚本 ssh 命令退出状态 [英] shell script ssh command exit status
问题描述
在 shell 脚本的循环中,我连接到各种服务器并运行一些命令.例如
In a loop in shell script, I am connecting to various servers and running some commands. For example
#!/bin/bash
FILENAME=$1
cat $FILENAME | while read HOST
do
0</dev/null ssh $HOST 'echo password| sudo -S
echo $HOST
echo $?
pwd
echo $?'
done
这里我正在运行echo $HOST"和pwd"命令,我通过echo $?"获得退出状态.
Here I am running "echo $HOST" and "pwd" commands and I am getting exit status via "echo $?".
我的问题是,我希望能够将远程运行的命令的退出状态存储在某个变量中,然后(根据命令是否成功)将日志写入本地文件.
My question is that I want to be able to store the exit status of the commands I run remotely in some variable and then ( based on if the command was success or not) , write a log to a local file.
感谢任何帮助和代码.
推荐答案
ssh
会以远程命令的退出码退出.例如:
ssh
will exit with the exit code of the remote command. For example:
$ ssh localhost exit 10
$ echo $?
10
所以在您的 ssh
命令退出后,您可以简单地检查 $?
.您需要确保没有掩盖您的返回值.例如,您的 ssh 命令以:
So after your ssh
command exits, you can simply check $?
. You need to make sure that you don't mask your return value. For example, your ssh command finishes up with:
echo $?
这将始终返回 0.您可能想要的是更像这样的:
This will always return 0. What you probably want is something more like this:
while read HOST; do
echo $HOST
if ssh $HOST 'somecommand' < /dev/null; then
echo SUCCESS
else
echo FAIL
done
你也可以这样写:
while read HOST; do
echo $HOST
if ssh $HOST 'somecommand' < /dev/null
if [ $? -eq 0 ]; then
echo SUCCESS
else
echo FAIL
done
这篇关于shell 脚本 ssh 命令退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!