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

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


The -m switch of PuTTY takes a path to a script file as an argument, not a command.

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

So you have to save your command (command_run) to a plain text file (e.g. c:\path\command.txt) and pass that to PuTTY:

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

Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).

A command-line syntax is identical, an output redirection added:

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

See Using the command-line connection tool Plink.

And with Plink, you can actually provide the command directly on its command-line:

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

Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file


You can also use Bash on Ubuntu on Windows directly. E.g.,

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

Per Martin Prikryl's comment below:

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.


As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run

Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.

Then you can create an ssh batch script such as

ECHO OFFCLS:MENUECHO.ECHO ........................ECHO SSH serversECHO ........................ECHO.ECHO 1 - Web Server 1ECHO 2 - Web Server 2ECHO E - EXITECHO.SET /P M=Type 1 - 2 then press ENTER:IF %M%==1 GOTO WEB1IF %M%==2 GOTO WEB2IF %M%==E GOTO EOFREM ------------------------------REM SSH Server detailsREM ------------------------------:WEB1CLScall ssh user@xxx.xxx.xxx.xxxcmd /k:WEB2CLScall ssh user@xxx.xxx.xxx.xxxcmd /k