Best Way to Script Remote Ssh Commands in Batch (Windows)

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

BATCH file to connect to Linux via SSH. How?

Firstly, do not name your batch file ssh.bat or ssh.cmd and it will probably be best if you use the full path to the executable:

@echo off
"C:\Windows\System32\OpenSSH\ssh.exe" -p 22 root@10.10.1.100
pause

but it is probably better to use the %windir% environment variable:

@echo off
"%windir%\System32\OpenSSH\ssh.exe" -p 22 root@10.10.1.100
pause

How to make a batch script to run commands on a remote machine using credentials

Try using PsExec
https://docs.microsoft.com/en-us/sysinternals/downloads/psexec

This is a light weight replacement for telnet

What is the cleanest way to ssh and run multiple commands in Bash?

How about a Bash Here Document:

ssh otherhost << EOF
ls some_folder;
./someaction.sh 'some params'
pwd
./some_other_action 'other params'
EOF

To avoid the problems mentioned by @Globalz in the comments, you may be able to (depending what you're doing on the remote site) get away with replacing the first line with

ssh otherhost /bin/bash << EOF

Note that you can do variable substitution in the Here document, but you may have to deal with quoting issues. For instance, if you quote the "limit string" (ie. EOF in the above), then you can't do variable substitutions. But without quoting the limit string, variables are substituted. For example, if you have defined $NAME above in your shell script, you could do

ssh otherhost /bin/bash << EOF
touch "/tmp/${NAME}"
EOF

and it would create a file on the destination otherhost with the name of whatever you'd assigned to $NAME. Other rules about shell script quoting also apply, but are too complicated to go into here.



Related Topics



Leave a reply



Submit