【问题标题】:how to execute if else condition with ssh to remote server如何使用 ssh 执行 if else 条件到远程服务器
【发布时间】:2013-12-11 17:54:35
【问题描述】:

我正在使用以下脚本远程连接到服务器,然后如果连接成功则回显成功,如果成功则尝试 sudo 文件 .如果连接失败,那么它应该回显失败。例如

#!/bin/sh
ssh -t -t rxapp@$1
'if [$? -eq 0 ];
then
echo "SUCCESS"
sudo /etc/init/ntp $2
else
echo "FAIL: Couldnot connect to remote server"
fi'

这里 $1 和 $2 在命令行中给出。 但这并没有成功。脚本只执行成功的 ssh 但不运行 sudo 和其他 echo 命令。 输出 : SSH 成功,但退出显示如下

./jenkins_ucf.sh: line 9: if [$? -eq 0 ];
then
echo "SUCCESS"
sudo /etc/init.d/unifiedCommFwk $2
else
echo "FAIL: COuldnot connect to remote server"
fi: No such file or directory

有什么帮助吗?或者它的任何替代方案也会有所帮助。

【问题讨论】:

  • 为什么是单引号? if [.......

标签: shell unix ssh


【解决方案1】:
#!/bin/sh
ssh -t -t rxapp@$1 "echo SUCCESS; /etc/init/ntp $2" || echo "FAIL: Could not connect to remote server"

if:

if ssh -t -t rxapp@$1 "echo SUCCESS; /etc/init/ntp $2"; then
    echo SUCCESS
else
    echo "FAIL: Could not connect to remote server"
fi

您需要将连接成功时在远程服务器上运行的部分与连接失败时在本地运行的部分分开。

【讨论】:

    【解决方案2】:

    如果您尝试使用反引号,则不需要 ' ' - 这也不是必需的。

    试试这个:

    ssh -t -t rxapp@$1
    if [ $? -eq 0 ];
    then
    echo "SUCCESS"
    sudo /etc/init/ntp $2
    else
    echo "FAIL: Couldnot connect to remote server"
    fi
    

    【讨论】:

      【解决方案3】:

      您可以像这样针对 SSH 服务器执行 if else 条件:

      ssh user@host 'bash -s' <<'ENDSSH'
      if [ someCommand ];
      then
        echo "SUCCESS"
      else
        echo "FAIL"
      fi'
      ENDSSH
      

      基本拉到from this answer

      【讨论】:

        【解决方案4】:

        简单地做

        ssh host -l username "if yourcommand; then echo Success; else echo Failure;fi"
        

        例如

        #!/bin/bash
        CMD="if $1; then echo Success; else echo Failure; fi"
        ssh host -l user "$CMD"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多