批量编写远程 SSH 命令脚本的最佳方式 (Windows)

Best way to script remote SSH commands in Batch (Windows)

我正在寻找批量脚本,这将需要在 Linux 上 运行 远程 ssh 命令。我想要输出 returned 以便我可以在屏幕上显示它或记录它。

我尝试了 putty.exe -ssh user@host -pw password -m command_run,但 return 我的屏幕上没有任何内容。

以前有人做过吗?

PuTTY 的 -m 开关将 脚本文件 的路径作为参数,而不是 命令

参考:https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m

因此您必须将命令 (command_run) 保存到纯文本文件(例如 c:\path\command.txt)并将其传递给 PuTTY:

putty.exe -ssh user@host -pw password -m c:\path\command.txt

但请注意,您应该使用 Plink(PuTTY 套件中的命令行连接工具)。它是一个控制台应用程序,因此您可以将其输出重定向到一个文件(PuTTY 无法做到这一点)。

命令行语法相同,添加了输出重定向:

plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt

Using the command-line connection tool Plink

使用 Plink,您实际上可以直接在其命令行上提供命令:

plink.exe -ssh user@host -pw password command > output.txt

类似问题:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file

作为替代选项,您可以安装 OpenSSH http://www.mls-software.com/opensshd.html 然后只需 ssh user@host -pw password -m command_run

编辑:安装时收到 user2687375 的响应后,仅 select 客户端。完成此操作后,您应该能够从命令启动 SSH。

然后你可以创建一个ssh批处理脚本如

ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.

SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF

REM ------------------------------
REM SSH Server details
REM ------------------------------

:WEB1
CLS
call ssh user@xxx.xxx.xxx.xxx
cmd /k

:WEB2
CLS
call ssh user@xxx.xxx.xxx.xxx
cmd /k

您也可以直接使用Bash on Ubuntu on Windows。例如,

bash -c "ssh -t user@computer 'cd /; sudo my-command'"

根据以下 Martin Prikryl 的评论:

The -t enables terminal emulation. Whether you need the terminal emulation for sudo depends on configuration (and by default you do no need it, while many distributions override the default). On the contrary, many other commands need terminal emulation.