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

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

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

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


当前回答

你可以使用runoverssh:

sudo apt install runoverssh
runoverssh -s localscript.sh user host1 host2 host3...

-s远程运行本地脚本


有用的标志: -g对所有主机使用全局密码(单密码提示) -n使用SSH代替sshpass,用于公钥认证

其他回答

答案在这里(https://stackoverflow.com/a/2732991/4752883),如果 您正在尝试使用plink或ssh在远程Linux机器上运行脚本。 如果脚本在linux上有多行,它就可以工作。

**但是,如果您试图运行位于本地的批处理脚本 linux/windows机器,而远程机器是windows,它由 使用**的多行

点击root@MachineB -m local_script.bat

不会工作。

只执行脚本的第一行。这可能是 丁克的限制。

解决方案1:

要运行多行批处理脚本(尤其是相对简单的脚本), 由几行组成):

如果您的原始批处理脚本如下

cd C:\Users\ipython_user\Desktop 
python filename.py

您可以使用“&&”分隔符将这些行组合在一起,如下所示 local_script.bat文件: https://stackoverflow.com/a/8055390/4752883:

cd C:\Users\ipython_user\Desktop && python filename.py

在此更改之后,您可以运行这里指出的脚本 @JasonR。Coombs: https://stackoverflow.com/a/2732991/4752883与:

`plink root@MachineB -m local_script.bat`

解决方案2:

如果批处理脚本相对复杂,使用批处理可能会更好 脚本,它封装了plink命令以及如下所指出的 这里由@Martin https://stackoverflow.com/a/32196999/4752883:

rem Open tunnel in the background
start plink.exe -ssh [username]@[hostname] -L 3307:127.0.0.1:3306 -i "[SSH
key]" -N

rem Wait a second to let Plink establish the tunnel 
timeout /t 1

rem Run the task using the tunnel
"C:\Program Files\R\R-3.2.1\bin\x64\R.exe" CMD BATCH qidash.R

rem Kill the tunnel
taskkill /im plink.exe

这是一个老问题,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

从@cglotr扩展答案。为了编写内联命令使用printf,它对简单的命令很有用,它支持多行使用字符转义'\n'

例子:

printf "cd /to/path/your/remote/machine/log \n tail -n 100 Server.log" | ssh <user>@<host> 'bash -s'

看,别忘了加上bash -s

你可以使用runoverssh:

sudo apt install runoverssh
runoverssh -s localscript.sh user host1 host2 host3...

-s远程运行本地脚本


有用的标志: -g对所有主机使用全局密码(单密码提示) -n使用SSH代替sshpass,用于公钥认证

另外,如果想从目标主机获取变量,不要忘记转义变量。

这在过去曾让我陷入困境。

例如:

user@host> ssh user2@host2 "echo \$HOME"

输出/home/user2

user@host> ssh user2@host2 "echo $HOME"

打印出/home/user

另一个例子:

user@host> ssh user2@host2 "echo hello world | awk '{print \$1}'"

正确地输出“hello”。