如何通过ssh执行远程命令?

时间:2017-07-21 07:20:49

标签: ssh

我尝试通过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" 但我一次只能执行一个命令。

...

反映意见

开发了一个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"

有什么更好的解决方案?

1 个答案:

答案 0 :(得分:0)

$ 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之间使用'的方式。