我必须在远程机器上运行本地shell脚本(windows/Linux)。
我在机器A和机器B上都配置了SSH。我的脚本在机器A上,它将在远程机器B上运行我的一些代码。
本地和远程计算机可以是基于Windows或Unix的系统。
是否有一种方法来运行这个使用plink/ssh?
我必须在远程机器上运行本地shell脚本(windows/Linux)。
我在机器A和机器B上都配置了SSH。我的脚本在机器A上,它将在远程机器B上运行我的一些代码。
本地和远程计算机可以是基于Windows或Unix的系统。
是否有一种方法来运行这个使用plink/ssh?
当前回答
如果脚本很短,并且打算嵌入到脚本中,并且您在bash shell下运行,并且bash shell在远程端可用,则可以使用declare将本地上下文传输到远程端。定义包含将传输到远程服务器的状态的变量和函数。定义一个将在远程端执行的函数。然后在bash -s读取的here文档中,您可以使用declare -p来传递变量值,并使用declare -f将函数定义传递到远程文件。
因为declare负责引用并将由远程bash解析,所以变量被正确引用,函数被正确传输。你可以只在本地写脚本,通常我在远程端做一个长函数。上下文需要精心挑选,但是下面的方法对于任何简短的脚本都“足够好”,而且是安全的——应该可以正确处理所有极端情况。
somevar="spaces or other special characters"
somevar2="!@#$%^"
another_func() {
mkdir -p "$1"
}
work() {
another_func "$somevar"
touch "$somevar"/"$somevar2"
}
ssh user@server 'bash -s' <<EOT
$(declare -p somevar somevar2) # transfer variables values
$(declare -f work another_func) # transfer function definitions
work # call the function
EOT
其他回答
如果Machine A是一台Windows机器,您可以使用Plink (PuTTY的一部分)和-m参数,它将在远程服务器上执行本地脚本。
plink root@MachineB -m local_script.sh
如果Machine A是一个基于unix的系统,你可以使用:
ssh root@MachineB 'bash -s' < local_script.sh
您不应该必须将脚本复制到远程服务器才能运行它。
答案在这里(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
chmod +x script.sh
ssh -i key-file root@111.222.3.444 < ./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"
如果它是一个脚本,那么上面的解决方案是没问题的。
我会安排Ansible来做这项工作。它以同样的方式工作(Ansible使用ssh在Unix或Windows的远程机器上执行脚本)。
它将更具结构化和可维护性。