我必须在远程机器上运行本地shell脚本(windows/Linux)。
我在机器A和机器B上都配置了SSH。我的脚本在机器A上,它将在远程机器B上运行我的一些代码。
本地和远程计算机可以是基于Windows或Unix的系统。
是否有一种方法来运行这个使用plink/ssh?
我必须在远程机器上运行本地shell脚本(windows/Linux)。
我在机器A和机器B上都配置了SSH。我的脚本在机器A上,它将在远程机器B上运行我的一些代码。
本地和远程计算机可以是基于Windows或Unix的系统。
是否有一种方法来运行这个使用plink/ssh?
当前回答
另外,如果想从目标主机获取变量,不要忘记转义变量。
这在过去曾让我陷入困境。
例如:
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”。
其他回答
首先,使用scp将脚本复制到机器B
[user@machineA]$ scp /path/to/script user@machineB:/home/user/path
然后,运行脚本
[user@machineA]$ ssh user@machineB "/home/user/path/script"
如果您已经为脚本授予了可执行权限,那么这将起作用。
假设您的意思是希望从“本地”机器自动执行此操作,而不需要手动登录到“远程”机器,那么您应该查看名为Expect的TCL扩展,它正是为这种情况而设计的。我还提供了一个通过SSH登录/交互的脚本链接。
https://www.nist.gov/services-resources/software/expect
http://bash.cyberciti.biz/security/expect-ssh-login-script/
这个bash脚本可以ssh到目标远程机器,并在远程机器上运行一些命令,在运行它之前不要忘记安装expect(在mac brew上安装expect)
#!/usr/bin/expect
set username "enterusenamehere"
set password "enterpasswordhere"
set hosts "enteripaddressofhosthere"
spawn ssh $username@$hosts
expect "$username@$hosts's password:"
send -- "$password\n"
expect "$"
send -- "somecommand on target remote machine here\n"
sleep 5
expect "$"
send -- "exit\n"
你可以使用runoverssh:
sudo apt install runoverssh
runoverssh -s localscript.sh user host1 host2 host3...
-s远程运行本地脚本
有用的标志: -g对所有主机使用全局密码(单密码提示) -n使用SSH代替sshpass,用于公钥认证
这是一个老问题,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