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

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

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

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


当前回答

chmod +x script.sh    
ssh -i key-file root@111.222.3.444 < ./script.sh

其他回答

chmod +x script.sh    
ssh -i key-file root@111.222.3.444 < ./script.sh

假设您的意思是希望从“本地”机器自动执行此操作,而不需要手动登录到“远程”机器,那么您应该查看名为Expect的TCL扩展,它正是为这种情况而设计的。我还提供了一个通过SSH登录/交互的脚本链接。

https://www.nist.gov/services-resources/software/expect

http://bash.cyberciti.biz/security/expect-ssh-login-script/

我用它在远程机器上运行一个shell脚本(在/bin/bash上测试):

ssh deploy@host . /home/deploy/path/to/script.sh

这个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"

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

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

例如:

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”。