【问题标题】:bash - Capture exit code from remote ssh commandbash - 从远程 ssh 命令捕获退出代码
【发布时间】:2016-12-12 10:14:15
【问题描述】:

我正在寻找在 shell 脚本中捕获远程 ssh 命令的退出状态 我有一个shell脚本如下:

function rSSH {
   local x
   echo "Running ssh command"
   x=$(ssh -o StrictHostKeyChecking=no -i $keyPair -o ProxyCommand="ssh -W %h:%p -i $keyPair user@$bastionIP 22" user@$IP "$cmd")

   x=$?
   echo "SSH status is : $x"
   if [ $x -eq 0 ];then
      echo "Success"

   else
      echo "Failure"
      exit 1
   fi
}

rSSH
exit 0

当我使用无效的 $bastionIP(测试失败场景)将上述脚本作为后台作业执行时,它的退出代码为 0(而不是 1),我在日志中看到的唯一信息是第一个回显“正在运行 ssh 命令”,它只是退出脚本。

有人可以指出我做错了什么或更好的方法来捕获远程 ssh 命令的退出状态。 感谢任何帮助。

【问题讨论】:

  • 你在用set -e吗?
  • 啊,是的。这可能是导致问题的原因。 @chepner 感谢您指出这一点。完全错过了

标签: linux bash shell ssh


【解决方案1】:

面临同样的问题。我必须通过远程 ssh 连接执行一系列命令,如下所示,脚本将在 'echo'ing the 'return here=' 之前终止。

ssh -v -T -i ${KEY} -p${PORT} -tt ${USER}@${IP} /bin/bash -c "'
echo "Inside Script"
exit 12
'"
echo "return here=$?"

感谢@chepner 在原帖中的回复,这与我使用的问题相同 set -e

删除它有助于解决。

【讨论】:

    【解决方案2】:

    脚本似乎在set -e 下运行,这意味着当ssh 连接失败时,脚本会立即退出。

    【讨论】:

      【解决方案3】:

      尝试使用另一个变量作为返回码。

      function rSSH {
         local x
         echo "Running ssh command"
         x=$(ssh -o StrictHostKeyChecking=no -i $keyPair -o ProxyCommand="ssh -W %h:%p -i $keyPair user@$bastionIP 22" user@$IP "$cmd")
      
         local ret_code
         ret_code=$?
         echo "SSH status is : $ret_code"
         if [ $ret_code -eq 0 ];then
            echo "Success"
      
         else
            echo "Failure"
            exit 1
         fi
      }
      
      rSSH
      exit 0
      

      【讨论】:

      • 为什么你的变量名x有问题?然后你也应该更改local
      • 你可以保留本地的。
      • 您需要更新它以将ret_code 也声明为本地。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      相关资源
      最近更新 更多