如何通过 ssh 执行远程命令? [英] How to execute a remote command over ssh?

查看:55
本文介绍了如何通过 ssh 执行远程命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如

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

效果很好,但我有以下问题

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

案例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"但我一次只能执行一个命令.

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

...

反映评论

开发了一个bash脚本

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?

推荐答案

$ 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的方式.

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 执行远程命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆