Create a batch file or shortcut to PuTTY (ssh) that opens a session and runs a command

10

8

I often find myself opening an SSH session to run the same single command. I have everything setup to login without entering a password (Via SSH Key-Based Auth), so I wondered if there was a way to create a shortcut or a batch file in Windows that would load PuTTY or a similar program, then fire off that command (and likely exit if result is good).

FreeSoftwareServers

Posted 2017-12-19T12:20:02.377

Reputation: 962

Answers

14

Use the commandline PuTTY version plink.exe to initate a SSH connection to a host of choice. Use the -ssh switch to connect with SSH. With the -m switch you can include a command file:

plink.exe -ssh host1 -m C:\path\to\commands.txt

You can download plink.exe from here.

Last step would be to create a shortcut including plink.exe with the desired parameters.

Check out the Plink documentation for other various parameters: Plink.exe documentation

Smeerpijp

Posted 2017-12-19T12:20:02.377

Reputation: 1 004

1

No need to use -m switch with Plink, as it allow to specify command directly on its command-line, see my answer.

– Martin Prikryl – 2017-12-19T15:15:46.867

I am choosing this answer as I prefer using -ssh host1 which relates to putty Profile vs user@host – FreeSoftwareServers – 2017-12-21T12:39:13.920

@FreeSoftwareServers There's no difference to PuTTY in this respect. You can do plink site command the same way as with PuTTY (except for command). Plink and PuTTY has basically the same set of command-line options. – Martin Prikryl – 2017-12-28T08:02:45.803

8

To automate a command execution, use Plink (from PuTTY package), not PuTTY itself.

Plink accepts a command on its command line:

plink.exe user@host command

If you want to keep using PuTTY, you can use -m switch to specify a command file (Plink supports the -m switch too).

Martin Prikryl

Posted 2017-12-19T12:20:02.377

Reputation: 13 764

When I said I had no password, I should have specified I meant with SSH Key-based Auth, but I figured it would be assumed. I don't think this would work as it is, it would need parameters added on like -i key or -pw password – FreeSoftwareServers – 2017-12-21T12:38:17.970

@FreeSoftwareServers There's no difference to PuTTY in this respect. You can do plink site command the same way as with PuTTY (except for command). Plink and PuTTY has basically the same set of command-line options. – Martin Prikryl – 2017-12-21T12:52:51.230

your answer did not include the options to use SSH Key Based Auth aka PWDless login, while the correct flags exist, i found them in the man pages for plink which was included in MrPowerUsers answer, I understand both could work but MrPower users answer fit my question better and linked the man pages as well – FreeSoftwareServers – 2017-12-28T08:06:22.613

6

You can use putty configurations to achieve this.

Load putty and configure your session.

Enter the remote command that you'd like to run here:

Putty remote command box

Then, before clicking "Open", go back to the "Session" tab (at the top), and save your configuration.

Now, create a shortcut to putty.exe, adding the -load flag, for example:

%PATH_TO_PUTTY%\putty.exe -load my_config

Now, you can just click on the shortcut and it will load your session, executing your command.

Attie

Posted 2017-12-19T12:20:02.377

Reputation: 14 841

Looks awesome, ill test tomorrow, i suppose i will just execute a script and it can end the session based on results of script – FreeSoftwareServers – 2017-12-19T12:45:09.687

Yes, the session will end when the command terminates. If you'd like PuTTY to hang around once done (e.g: to inspect the output), then set "Close window on exit" in the "Session" tab. – Attie – 2017-12-19T14:09:48.550

2

If you're using Windows 10, you might be interested to know that Microsoft reportedly has a beta of OpenSSH (client and server):

[…] go to “Manage Optional Features” then + “Add a feature”. You can then scroll down the list and find the OpenSSH Client (Beta) and OpenSSH Server (Beta) features in Windows. The idea of running another remote service on Windows can be daunting so we do not blame you if you do not want to install the server.

Once installed, you can simply fire up your command line and use the OpenSSH client by typing ssh followed by the command such as ssh ubuntu@someIP.

Here is the current (as of November 28, 2017) ssh command usage guide we are getting with the Windows OpenSSH Client:

C:\WINDOWS\system32>ssh
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
           [-D [bind_address:]port] [-E log_file] [-e escape_char]
           [-F configfile] [-I pkcs11] [-i identity_file]
           [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
           [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
           [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
           [user@]hostname [command]
C:\WINDOWS\system32>

If this works, you should be able to use ssh like you would on a *Nix:

C:\WINDOWS\system32>ssh user@host "ls -l ~"

Michael - Where's Clay Shirky

Posted 2017-12-19T12:20:02.377

Reputation: 491

Thats really cool to know, but I love SuperPuTTY. I will keep an eye on Windows OpenSSH as well. – FreeSoftwareServers – 2017-12-21T12:18:44.927

Do you need to have the ssh client on the machine you are remoting into? I ask because some of the machines I remote into are not Windows 10. – Nelda.techspiress – 2019-07-30T14:40:04.460

1@Nelda.techspiress You should only need the server running on machines you log in to and only need the client on machines you log in from. (Correspondingly, if you log into one machine as a proxy to hop into another one, that middle machine will need both.) – Michael - Where's Clay Shirky – 2019-07-30T18:03:16.123

2

Just thought I'd insert the script I made to hopefully save some people hours of syntax and man page research

a) SingleIP, IP Range, or IPList file

b) script name to run on the IP/range (actual unix sh/ksh type script)

c) optionally do nmap scan for port 22 open (i.e. subnet with some non-Linux machines)

-want to avoid IPs putty cannot connect to, avoiding script being able to continue properly

d) optionally run pscp command to autocache the host key (putty does not do this automatically)

This batch assumes:

1. you have the full PuTTY package and SSH key installed in C:\Program Files\PuTTY\

2. batch/scripts/IPlist files installed in C:\Program Files\PuTTY\scripts\

3. The NMAP and PuTTY working directories are in your command path

https://www.harmonyhit.com/PuttyBatch.bat

This is mostly useful for having a single script (such as updating an SSL certificate) across a range of machines

Here is complete batch file:

@ECHO OFF

rem  You must modify the CACHEKEY and SCRIPT section to reflect your SSH key location

set IPFILE=IPList_temp.txt
set runagain=n
set OPTION=1
set RANGE=
set IP=
set SCAN=n
set KEYCACHE=n

:OPTION
CLS
ECHO (Working directory is set to C:\Program Files\PuTTY\scripts\)
ECHO. 
ECHO 1. Single IP
ECHO 2. IP list file
ECHO 3. IP Range
ECHO.
set /p OPTION="Choose IP type:"
IF %OPTION%==3 GOTO IPRANGE
IF %OPTION%==2 GOTO IPLIST
IF %OPTION%==1 GOTO SINGLEIP
echo Please select a valid option
GOTO OPTION

:IPRANGE
ECHO Enter the IP range(s) as in the following example. Use a space between multiple ranges:
ECHO       i.e. "10.21.0.15-99 10.21.1.15-100"
set /p RANGE=Enter Range: 
echo %RANGE% > %IPFILE%
GOTO SCRIPTNAME

:SINGLEIP
set /p IP=Enter IP:
echo %IP% > %IPFILE%
GOTO SCRIPTNAME

:IPLIST
set /p IP=Enter IPList filename:
copy /Y %IP% %IPFILE%
GOTO SCRIPTNAME

:SCRIPTNAME
set /p SCRIPT=Enter script name:
if not exist %SCRIPT% (
echo filename does not exist!
GOTO SCRIPTNAME )

ECHO.
set /p SCAN=Do Nmap scan first? (recommended):
if %SCAN%==n GOTO :RUNCACHE

rem Check whether IP type is "range" as nmap cannot read an IP range from file and must be type directly in nmap command
IF %OPTION%==3 GOTO NMAPRANGE 
:NMAP
echo Scanning IPs for port 22 open...
nmap --open -n -p22 -iL %IPFILE% -oG - | findstr /E Up > nmap_temp.txt
GOTO AFTERNMAP

:NMAPRANGE
echo Scanning IPs for port 22 open...
nmap --open -n -p22 %RANGE% -oG - | findstr /E Up > nmap_temp.txt

:AFTERNMAP
echo DONE
rem     nmap formatting is not correct, the following removes extra info
for /f "tokens=2" %%A in (nmap_temp.txt) do echo %%A >> nmap_temp2.txt
rem remove hidden space at end of IP (requires "repl" be in the batch file directory)
type "nmap_temp2.txt" | repl " " "" > %IPFILE%

:RUNCACHE
set /p KEYCACHE=Scan and cache SSH key (y/n) ?
if %KEYCACHE%==n GOTO SCRIPT

:CACHEKEY
rem Run through all IPs to cache the SSH Host Key if not already cached
for /F "tokens=*" %%A in (%IPFILE%) do ( echo y | "C:\Program Files\PuTTY\pscp.exe" -l root -i "C:\Program Files\PuTTY\SSH.ppk" -touch %%A:/tmp/test )

:SCRIPT
for /F "tokens=1" %%A in (%IPFILE%) do ( "C:\Program Files\PuTTY\putty.exe" -ssh %%A -t -l root -i "C:\Program Files\PuTTY\SSH.ppk" -m "C:\Program Files\PuTTY\scripts\%SCRIPT%" )
if exist nmap_temp.txt (del nmap_temp.txt)
if exist nmap_temp2.txt (del nmap_temp2.txt)
set /p runagain="Press Enter to Finish or y to rerun"
if %runagain%==y GOTO OPTION

Todd Porter

Posted 2017-12-19T12:20:02.377

Reputation: 21

1Link only answers are frowned upon, what if your site goes down? If you want to contribute, please share the script here. Your welcome to post a source/link to the site along with the code here, but answers should be self-contained and not require following links. – FreeSoftwareServers – 2019-06-05T07:55:05.393

1batch contents pasted – Todd Porter – 2019-06-05T18:44:03.183

Do not "autocache" a host key. Verifying host key is an integral part of securing your SSH session. PuTTY (and its tools) do not ask you for the host key for fun or to harass you. It has a reason! + You also should not store user data (SSH.ppk and the script) toProgram Files` folder. – Martin Prikryl – 2019-06-06T04:52:29.010

can you recommend how to run a script across multiple IPs without it? a) this is not meant for a typical user desktop, more for an admin server where security is more who has access to the server b) what exactly IS the security risk? Caching the host key is optional and should only be done once across the range. If you run the script again without caching the key you will still see and host key changes and the script will not continue on... – Todd Porter – 2019-06-07T16:04:31.660

......In agreement on the key thou. I point to a shared folder on our NAS where the shared folder lives, which only I have access to. I just picked a path since other users will be different – Todd Porter – 2019-06-07T16:24:54.797

1

You can also look at software such as mRemoteNG, MOBAxTerm or SecureCRT which will manage your SSH connections for you, this also links with the saved PuTTY sessions so you can apply a template to the session.

Gubbins

Posted 2017-12-19T12:20:02.377

Reputation: 61

0

This is the final "CMD" which I can just save on my FileServer and create a shortcut on my Desktop.

::FreeSoftwareServers
::Automated Opening of SSH Tunnel & Execute CMD on Remote Host
::https://superuser.com/questions/1278434/create-a-batch-file-or-shortcut-to-putty-ssh-that-opens-a-session-and-runs-a-c

set puttydir="C:\Program Files\PuTTY"
set exe=plink.exe
::Profile must exist in PuTTY
set remotehost=FileServer
set remotecmd="chmod 777 /mnt/mdadm/torrents -R"

cd %puttydir% 

%exe% %remotehost% %remotecmd%

::Test First Manually in CMD Prompt
::Note Remote Host does NOT have access to BashRC Alias's
::start "C:\Program Files\PuTTY\" plink.exe -ssh FileServer touch /tmp/testfile
::start "C:\Program Files\PuTTY\" plink.exe -ssh FileServer ~/script.sh

FreeSoftwareServers

Posted 2017-12-19T12:20:02.377

Reputation: 962