【问题标题】:How to execute a remote command over ssh?如何通过 ssh 执行远程命令?
【发布时间】:2017-07-21 07:20:48
【问题描述】:

我尝试通过 ssh 连接到远程服务器并执行命令。

但是鉴于这种情况,我只能执行一个命令。

例如

ssh -i ~/auth/aws.pem ubuntu@server "echo 1"

效果很好,但是下面的我有问题

案例1

ssh -i ~/auth/aws.pem ubuntu@server "cd /"

ssh -i ~/auth/aws.pem ubuntu@server "ls"

案例2

ssh -i ~/auth/aws.pem ubuntu@server "export a=1"

ssh -i ~/auth/aws.pem ubuntu@server "echo $a"

会话未维护。

当然,你可以使用“cd /; ls” 但我一次只能执行一个命令。

...

反映cmets

开发了一个 bash 脚本

function cmd()
{
    local command_delete="$@"

    if [ -f /tmp/variables.current ]; then
        set -a
        source /tmp/variables.current
        set +a
        cd $PWD
    fi

    if [ ! -f /tmp/variables.before ]; then
        comm -3 <(declare | sort) <(declare -f | sort) > /tmp/variables.before
    fi

    echo $command_delete > /tmp/export_command.sh

    source /tmp/export_command.sh

    comm -3 <(declare | sort) <(declare -f | sort) > /tmp/variables.after

    diff /tmp/variables.before /tmp/variables.after \
                        | sed -ne 's/^> //p' \
                        | sed '/^OLDPWD/ d' \
                        | sed '/^PWD/ d' \
                        | sed '/^_/ d' \
                        | sed '/^PPID/ d' \
                        | sed '/^BASH/ d' \
                        | sed '/^SSH/ d' \
                        | sed '/^SHELLOPTS/ d' \
                        | sed '/^XDG_SESSION_ID/ d' \
                        | sed '/^FUNCNAME/ d' \
                        | sed '/^command_delete/ d' \
                        > /tmp/variables.current

    echo "PWD=$(pwd)" >> /tmp/variables.current
}

ssh -i ~/auth/aws.pem ubuntu@server "cmd cd /"

ssh -i ~/auth/aws.pem ubuntu@server "cmd ls"

还有什么更好的解决方案?

【问题讨论】:

  • 您是否在问如何通过 SSH 进行交互式会话?如果是这样,只需省略命令即可连接。
  • 我只能执行一个命令
  • 只需使用ssh -i ~/auth/aws.pem ubuntu@server,您将拥有一个交互式会话。这是你想要达到的目标吗?
  • 没有。执行任务命令,而不是键盘输入。

标签: ssh


【解决方案1】:
$ cat <<'EOF' | ssh user@server
export a=1
echo "${a}"
EOF
Pseudo-terminal will not be allocated because stdin is not a terminal.
user@server's password: 
1

通过这种方式,您会将所有命令作为单个文件脚本发送到ssh,因此您可以放置​​任意数量的命令。请注意在单引号'之间使用EOF的方式。

【讨论】:

  • 单个命令是什么意思?这是单个命令:export a=1; echo "${a}"?
  • 为什么只能执行一个命令?什么是重串它?
  • 简单地说——你不能。变量仅在当前会话中退出。作为一种解决方法,您可以使用文件在会话之间存储数据。像“echo 1>/tmp/a”然后是“echo cat /tmp/a
猜你喜欢
  • 1970-01-01
  • 2022-01-08
  • 2021-02-23
  • 1970-01-01
  • 2013-09-01
  • 2013-11-22
  • 2015-07-25
  • 1970-01-01
相关资源
最近更新 更多