【发布时间】:2015-03-27 15:57:42
【问题描述】:
我正在寻找需要在 Linux 上运行远程 ssh 命令的批处理脚本。我希望返回输出,以便可以在屏幕上显示或记录它。
我尝试了putty.exe -ssh user@host -pw password -m command_run,但它没有在我的屏幕上返回任何内容。
以前有人做过吗?
【问题讨论】:
标签: linux windows batch-file ssh putty
我正在寻找需要在 Linux 上运行远程 ssh 命令的批处理脚本。我希望返回输出,以便可以在屏幕上显示或记录它。
我尝试了putty.exe -ssh user@host -pw password -m command_run,但它没有在我的屏幕上返回任何内容。
以前有人做过吗?
【问题讨论】:
标签: linux windows batch-file ssh putty
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
【讨论】:
您也可以直接使用Bash on Ubuntu on Windows。例如,
bash -c "ssh -t user@computer 'cd /; sudo my-command'"
根据 Martin Prikryl 的评论如下:
-t 启用终端仿真。您是否需要 sudo 的终端仿真取决于配置(默认情况下您不需要它,而许多发行版会覆盖默认值)。相反,许多其他命令需要终端仿真。
【讨论】:
-t 启用终端仿真。是否需要 sudo 的终端仿真取决于配置(默认情况下您不需要它,而许多发行版会覆盖默认值)。相反,许多其他命令需要终端仿真。所以你的最后一段是非常不正确的。无论如何 +1。
-t 所做的事情之前,我应该先拥有ssh --help!用您的信息更新答案。
作为替代选项,您可以安装 OpenSSH http://www.mls-software.com/opensshd.html,然后只需安装 ssh user@host -pw password -m command_run
编辑:在安装时收到user2687375 的响应后,仅选择客户端。完成此操作后,您应该能够从命令启动 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
【讨论】:
-ssh user@host -pw password -m c:\path\command.txt