How to execute a remote command over ssh?

2019-09-15 00:03发布

问题:

I try to connect to the remote server by ssh and execute the command.

But given the situation, I can only execute a single command.

For example

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

It works very well, but I have a problem with the following

case1

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

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

case2

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

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

The session is not maintained.

Of course, you can use "cd /; ls" but I can only execute one command at a time.

...

Reflecting comments

developed a bash script

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"

What better solution?

回答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

In this way you will send all commands to ssh as a single file script, so you can put any number of commands. Please note the way to use EOF between single quote '.



标签: ssh