Using Bat for simple SSH commands on multiple servers

Requires; plink

This bat script will allow you to quickly perform tasks on multiple servers. This will save you time if you are currently still using Putty or something similar to log into each server individually all the time, to execute a command on each one.

First, we create a menu with server choices.

———————————–

@echo off
goto menu1
:menu1
echo 1 server1
echo 2 server2
echo 3 server3
echo 4 server4
echo.

:choice
set /P C=[Pick a number]?
if "%C%"=="1" goto server1
if "%C%"=="2" goto server2
if "%C%"=="3" goto server3
if "%C%"=="4" goto server4
goto choice

———————————–

Define what to set the “serveraddr” and “serverpw” variables to based on which server was picked.

———————————–

:server1
set serveraddr=xxx.xxx.xxx.xxx
set serverpw=xxx
goto menu2

:server2
set serveraddr=xxx.xxx.xxx.xxx
set serverpw=xxx
goto menu2

:server3
set serveraddr=xxx.xxx.xxx.xxx
set serverpw=xxx
goto menu2

:server4
set serveraddr=xxx.xxx.xxx.xxx
set serverpw=xxx
goto menu2

———————————–

Create a second menu with options for what to do on the selected server. In my case I add commands to stop, start or restart squid, because I run squid on all my servers. I also add the choice to just open SSH so I can input a custom command. Do note that things like “vim” will not work over cmd so this is really just for command line usage.

———————————–

:menu2
echo 1 Restart Squid
echo 2 Stop Squid
echo 3 Start Squid
echo 4 Login SSH
echo.

:choice
set /P C=[Pick a number]?
if "%C%"=="1" goto restartsquid
if "%C%"=="2" goto stopsquid
if "%C%"=="3" goto startsquid
if "%C%"=="4" goto loginssh
goto choice

———————————–

So finally we add the actions to perform based on which number was picked. My plink is in E:\ so don’t forget to edit it to represent your plink’s location. Also don’t forget to change “root” into your actual username if yours is different. If you use a different username on various servers you will need to add another variable for it.

———————————–

:restartsquid
E:\plink.exe root@%serveraddr% -pw %serverpw% /etc/init.d/squid restart
echo.
goto menu2

:stopsquid
E:\plink.exe root@%serveraddr% -pw %serverpw% /etc/init.d/squid stop
echo.
goto menu2

:startsquid
E:\plink.exe root@%serveraddr% -pw %serverpw% /etc/init.d/squid start
echo.
goto menu2

:loginssh
E:\plink.exe root@%serveraddr% -pw %serverpw%

———————————–

Leave a Reply

Your email address will not be published. Required fields are marked *