【问题标题】:check SSH connection and call function, execute command检查SSH连接和调用函数,执行命令
【发布时间】:2015-01-07 17:35:44
【问题描述】:

我在配置 RSA 连接后尝试 SSH 客户端。我想验证 SSH 连接是否成功,如果是,那么想先通过调用一个函数来获取它,然后在客户端上执行命令。下面是我试图在服务器上执行的脚本,

function set_env() {
        if [ -f /usr/pw/server/bin/setup_env.sh ]; then
                        source /usr/pw/server/bin/setup_env.sh
        elif [ -f /etc/mcell/setup_env.sh ]; then
                        source /etc/mcell/setup_env.sh
        else
                        echo "setup_env.sh not found, exiting"
                        exit 1
        fi
}

i="application_was"

if ssh clientname
then
        set_env
        mcstat -q -n $i | grep "Running"
else
        echo "Sorry"
fi

我可以通过 SSH 连接到客户端,但登录时客户端没有执行 set_env 功能。我如何确保它发生?如果没有,如何捕获错误?

【问题讨论】:

  • 使用expect(1) 编写交互式程序的脚本。

标签: linux bash shell ssh


【解决方案1】:

假设这一切都应该在远程机器上运行,那么你需要把它全部放在远程命令中。

当在非交互式上下文中运行时,ssh 不会神奇地放入远程主机上的 shell 以执行其余的运行脚本(想想它需要如何工作一分钟)。

ssh clientname '
    if [ -f /usr/pw/server/bin/setup_env.sh ]; then
        source /usr/pw/server/bin/setup_env.sh
    elif [ -f /etc/mcell/setup_env.sh ]; then
        source /etc/mcell/setup_env.sh
    else
        echo "setup_env.sh not found, exiting"
        exit 1
    fi
    mcstat -q -n "'"$i"'" | grep "Running"' || echo "Sorry"

如果 ssh 连接失败或采购失败,或者如果 grep 失败并且在所有其他情况下输出 grep,这将为您输出“抱歉”。

【讨论】:

  • 感谢@Etan Reisner,但它不会为 i 保存变量值。我可以在 SSH 命令中传递变量吗?
  • 已编辑以使用当前 shell 中的变量。如果可能的话,直接在命令中内联名称可能会更好。
猜你喜欢
  • 2014-09-02
  • 1970-01-01
  • 2012-07-29
  • 2019-06-10
  • 2022-08-23
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多