我必须在远程机器上运行本地shell脚本(windows/Linux)。
我在机器A和机器B上都配置了SSH。我的脚本在机器A上,它将在远程机器B上运行我的一些代码。
本地和远程计算机可以是基于Windows或Unix的系统。
是否有一种方法来运行这个使用plink/ssh?
我必须在远程机器上运行本地shell脚本(windows/Linux)。
我在机器A和机器B上都配置了SSH。我的脚本在机器A上,它将在远程机器B上运行我的一些代码。
本地和远程计算机可以是基于Windows或Unix的系统。
是否有一种方法来运行这个使用plink/ssh?
当前回答
我用它在远程机器上运行一个shell脚本(在/bin/bash上测试):
ssh deploy@host . /home/deploy/path/to/script.sh
其他回答
如果它是一个脚本,那么上面的解决方案是没问题的。
我会安排Ansible来做这项工作。它以同样的方式工作(Ansible使用ssh在Unix或Windows的远程机器上执行脚本)。
它将更具结构化和可维护性。
如果你想这样执行命令 temp = ' ls - a ' echo $临时 ' '中的命令将导致错误。
下面的命令将解决这个问题 SSH user@host " ' temp = ' ls - a ' echo $临时 “‘
另外,如果想从目标主机获取变量,不要忘记转义变量。
这在过去曾让我陷入困境。
例如:
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”。
这个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"
从@cglotr扩展答案。为了编写内联命令使用printf,它对简单的命令很有用,它支持多行使用字符转义'\n'
例子:
printf "cd /to/path/your/remote/machine/log \n tail -n 100 Server.log" | ssh <user>@<host> 'bash -s'
看,别忘了加上bash -s