我必须在远程机器上运行本地shell脚本(windows/Linux)。

我在机器A和机器B上都配置了SSH。我的脚本在机器A上,它将在远程机器B上运行我的一些代码。

本地和远程计算机可以是基于Windows或Unix的系统。

是否有一种方法来运行这个使用plink/ssh?


当前回答

尝试运行ssh user@remote sh ./script. unix。

其他回答

还有另一种方法,您可以使用scp命令将脚本复制到主机中,然后轻松执行。

本地脚本是否使用本地设置的变量、函数或别名尚不清楚。

如果它这样做,应该工作:

myscript.sh:

#!/bin/bash

myalias $myvar
myfunction $myvar

它使用$myvar, myfunction和myalias。让我们假设它们是在本地设置的,而不是在远程机器上。

创建一个包含脚本的bash函数:

eval "myfun() { `cat myscript.sh`; }"

设置变量、函数和别名:

myvar=works
alias myalias='echo This alias'
myfunction() { echo This function "$@"; }

使用env_parallel从GNU Parallel中导出myfun, myfunction, myvar和myalias到服务器:

env_parallel -S server -N0  --nonall myfun ::: dummy

这是一个老问题,Jason的回答很好,但我想补充一点:

ssh user@host <<'ENDSSH'
#commands to run on remote host
ENDSSH

这也可以用于su和需要用户输入的命令。(注意此处的“转义”)

由于这个答案不断获得流量,我将为heredoc的美妙用法添加更多信息:

您可以使用这种语法嵌套命令,这是嵌套工作的唯一方式(以一种理智的方式)

ssh user@host <<'ENDSSH'
#commands to run on remote host
ssh user@host2 <<'END2'
# Another bunch of commands on another host
wall <<'ENDWALL'
Error: Out of cheese
ENDWALL
ftp ftp.example.com <<'ENDFTP'
test
test
ls
ENDFTP
END2
ENDSSH

实际上,您可以使用telnet、ftp等服务进行对话。但是记住,heredoc只是将stdin作为文本发送,它并不等待行间的响应

我刚刚发现,如果你使用<<-END!

ssh user@host <<-'ENDSSH'
    #commands to run on remote host
    ssh user@host2 <<-'END2'
        # Another bunch of commands on another host
        wall <<-'ENDWALL'
            Error: Out of cheese
        ENDWALL
        ftp ftp.example.com <<-'ENDFTP'
            test
            test
            ls
        ENDFTP
    END2
ENDSSH

(我认为这应该可行)

也看到 http://tldp.org/LDP/abs/html/here-docs.html

cat ./script.sh | ssh <user>@<host>
<hostA_shell_prompt>$ ssh user@hostB "ls -la"

这将提示您输入密码,除非您已经将hostA用户的公钥复制到用户.ssh目录的home目录下的authorized_keys文件。这将允许无密码身份验证(如果在ssh服务器的配置上接受作为身份验证方法)。