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

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

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

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


当前回答

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

其他回答

我已经开始使用Fabric进行更复杂的操作。Fabric需要Python和一些其他依赖项,但仅在客户机上。服务器只需为ssh服务器即可。我发现这个工具比交付给SSH的shell脚本强大得多,并且非常值得费心设置(特别是如果您喜欢用Python编程)。Fabric处理在多个主机(或具有某些角色的主机)上运行的脚本,帮助促进幂等操作(例如向配置脚本添加一行,但如果已经有一行就不行),并允许构造更复杂的逻辑(例如Python语言可以提供的逻辑)。

这个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"
chmod +x script.sh    
ssh -i key-file root@111.222.3.444 < ./script.sh

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

例子:

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

看,别忘了加上bash -s

ssh user@hostname ". ~/.bashrc;/cd path-to-file/;. filename.sh"

强烈建议使用环境文件(.bashrc/.bashprofile/.profile)。在远程主机上运行某些东西之前,因为目标主机和源主机的环境变量可能会延迟。