I have a friend in the Microsoft world that has to SSH to several servers and then tunnel Remote Desktop through the SSH tunnel. He does this with the ssh client PuTTY (http://www.chiark.greenend.org.uk/~sgtatham/putty/) and the ssh server from bitvise (http://www.bitvise.com/ssh-server-download). I was goofing around with writing a windows batch script to make the process easier and faster, and thought I’d use it to make a short intro to making batch files. You can use the examples here to make lots of your own little tools to accomplish tasks for users. I’ve done this in the past with allowing a user to encrypt a file or dynamically changing the DNS server. There’s no limit to what you can dream up.
I have added some features in this .bat file that you don’t really need only to show you what’s possible and give you some ideas.
We write these in Notepad. Once it’s all in, we “save as” and select “all files” instead of .txt. Name your file with a .bat extension (Gorilla_ssh.bat for example) and you have a finished product. So open up notepad and get started.
Let’s walk it a few lines at the time.
REM***SSH bat from Gorilla Admin
REM***Created 30 February 1492
REM***This bat file will ssh to the selected server
REM***UAC is not necessary for this file to work
This is the header of our batch file. When you type REM, the CMD shell will ignore anything after that. So we put things here to remind ourselves why something is the way it is, or to give information to folks that may be looking at what we did.
So now, just for fun lets set a title and color.
@echo off
color 0A
TITLE Gorilla Admin, SSH
The “@echo off” just tells the cmd shell not to print the command that is is currently executing. I chose a black background with green writing because I’m old school. You can pick other colors. A good place to find out what you can use is here:
http://www.robvanderwoude.com/ntcolor.php
The TITLE command will place whatever you tel it to at the top of the CMD window. We simply use Gorilla Admin, SSH.
We now set a place marker with something called a label. Labels start with “ : ”.
:Begin
We set this so that we can tell the CMD shell to come back to this spot if the user does something we don’t like, or makes a mistake. I’m just calling my label :Begin. I have another label at the bottom called :END.
Now we set some variables, and give them values.
SET Target=0
SET Location=Unknown
SET Answer=False
SET Continue=False
Some folks will tell you that the variable don’t have to have values yet. I will tell you that about 15 percent of the time, I have issues with empty variables, so I just eliminate that with prepopulated values. You can put them in the body of the batch file next to where you will be using them. But I learned a long time ago, that if you have to change them, it’s better to have them all up top rather than having to search through the body of the file. Here I’m saying set the value of Target to be 0, and set the value of location to be unknown, etc.
Now we give some instructions to the user with the “echo” command.
echo Choose 1 for HOME
echo Choose 2 for WORK
echo Choose 3 for PLAY
echo.
The echo command prints out everything after it to the screen. The echo command with a dot right after it, just means to skip a line. I use these for spacing so my text doesn’t look all run together and confusing. So what we did was ask our user which of the three servers he wants to log onto. Home, work or play?
Now the user has to answer and we have to store that answer in a variable.
set /p Target=Select the SSH target for your session, or (Q) to quit:
echo.
The set /p command will change the value of the variable Target (we gave it a value of 0 up top) to whatever the user types in. We also here offer the user the chance to quit instead of continuing. We could have made that an option for “Choose 4 to quit”, but I left that off so that if we need to add newer servers, I don’t have to rewrite as much and only add that info.
What this looks like to the user is this:
Choose 1 for HOME
Choose 2 for WORK
Choose 3 for PLAY
Select the SSH target for your session, or (Q) to quit:
Once the user types in a variable, we begin some checks to see if the user did what we wanted by typing in a correct option. We’ll start with the correct options, and then later talk about incorrect user input.
if %Target% == Q (goto :END)
if %Target% == q (goto :END)
if %Target% == 1 (SET Location=HOME
SET IP=192.168.1.1
SET Hostname=server)
if %Target% == 2 (SET Location=WORK
SET IP=172.16.8.1
SET Hostname=WORK-svr)
if %Target% == 3 (SET Location=PLAY
SET IP=10.20.30.1
SET Hostname=PLAY-SVR-01)
So, basically we have a few things going on here, all based off “IF”. The first two statements tell us IF the user typed a Q or a q, to go to the label :END, which we placed at the bottom of the script. That ends the execution. Notice that our variable has to be included between two % signs. I don’t know why this is, it’s just windows. All variables have to be called this way. So %Target% is the same Target that we got input from the user about, and declared as 0 at the top.
If %Target% is not a Q or q, then we check to see if it’s a 1. If it is, we assign values (with the SET command) to variables based on what is required to ssh to home. The three values we set are a site name, IP address to the site, and what the name of the server at the site is that we’ll want to Remote Desktop to connect to once the ssh tunnel is up. We repeat this for a choice of 2 or 3.
Notice that after the IF, we have a statement that “IF” true, we execute everything between the ( and ). So basically it’s:
IF ThisThing==True (then do this. And this. And this too.) REM but not this because I’m outside the parentheses.
Don’t forget the double equals sign. It’s important.
Now what if the user enters something we don’t expect? Notice that we set the variable “Location” to “Unknown” at the top of our script. If the user makes a valid choice, that value gets changed to something else. If they make an invalid choice, that variable %Location% still contains “Unknown”.
if %Location% == Unknown (cls
echo You have made an invalid selection, please try again.
echo.
echo Resetting..
ping -n 3 127.0.0.1>nul
cls
echo You have made an invalid selection, please try again.
echo.
echo Resetting....
ping -n 3 127.0.0.1>nul
cls
echo You have made an invalid selection, please try again.
echo.
echo Resetting......
ping -n 3 127.0.0.1>nul
echo.
goto :Begin)
So here, we know that since the user didn’t make a valid choice, that this very long if statement will be run. This is unnecessarily long. But we are doing it for learning’s sake. It’s basically the same routine three times (yes, we could have done this with a loop, I’m staying basic here). At the end of the IF statement, we are told to go back to the label “:Begin”, which basically starts us over.
So lets look at what the IF statement does. CLS erases the screen. You know what echo does and the only thing we change here is to add two dots at the end of “Resetting”. The sly little trick here is the 3 pings to the loopback address. The output is redirected to the black hole called nul. But the fun thing is that for three seconds, the batch file waits. So basically, what we have here is a crude, unnecessary animation that penalizes the user nine seconds for making a wrong choice. Is that mean? Nah, people need a break if even nine seconds.
At the end of the If statement, the user starts all over again and gets to either get it right this time, or quit entirely. Let’s assume that the user enters 1, 2, or 3, and we’ll move on by showing the user what she selected, and asking her if it’s right.
echo You have selected: %Target% for %Location%
echo.
echo Is this correct?
echo.
set /p Answer=(Y)es to continue, (Q)quit to end, or any other key to retry:
echo.
So none of this is new. We got values for %Target% and %Location% or we wouldn’t be here. So what the user would see, if we selected “3” for example would be:
You have selected: 3 for PLAY
Is this correct?
(Y)es to continue, (Q)quit to end, or any other key to retry:
As you see above, we’ll once again use “set /p” to change the value of %Answer% based off the user’s input. The user simply follows the instructions, and as before, we continue based off what the user inputs.
if %Answer% == Q (goto :END)
if %Answer% == q (goto :END)
if %Answer% == Y (SET Continue=True)
if %Answer% == y (SET Continue=True)
if %Answer% == Yes (SET Continue=True)
if %Answer% == yes (SET Continue=True)
if %Answer% == YES (SET Continue=True)
First, remember that we set the value for %Answer% to False way up at the top of the batch file. So unless the user chages it here, it’s still set to false. So we are back to the IF statements. I made this so if the user types Q or q, the script ends again. I also made it so that most variations of the word yes would change the value of Continue (again set to False up top) to True. If the user does’nt change it to True, the value remains false, and we continue.
if NOT %Continue% == True (echo Retrying...
echo.
goto :Begin)
This IF statement only triggers if %Continue% is still false. In other words NOT == True. If the user said that they selected the right server, then this statement won’t do anything. If the user “hit any other key”, meaning they wanted to retry, then %Continue% is NOT equal to true, and we go back to our old friend :Begin to start all over. We also echo Retrying, but since we did not cls or ping to slow it down, the user may not even notice.
But let’s assume our user typed “Y” and we’ll move on. We have the right location. We have the right IP address. We have the correct server to tunnel to. The user has confirmed that it’s all right. It’s time to make a connection and a little extra.
echo Trying %Location% at %IP%
start mstsc.exe
cd "c:\Program Files\PuTTY\"
putty.exe -L 9001:%Hostname%:3389 -P 22 %IP%
So, just to give the user some feedback, we echo the location and IP address back to the user. But the next line does something a little cool. Since we know the user is going to use remote desktop, we go ahead and open it up for her using the start command. Mstsc.exe is Microsoft Terminal Services Client, or more commonly known as Remote Desktop. Don’t say I never teach you anything useful for Geek Trivia night. Remote Desktop will launch in a separate window, obviously.
You can use the start command to launch anything. But calc.exe would not really do much for us here.
The next line jumps into the directory that PuTTY is in with the cd command. Naturally, your’s may be slightly different. The next line may be difficult to follow if you don’t understand networking well. But basically it says:
“Hey PuTTY, Listen on port 9001 and whatever hits that port, push it through the ssh connection to the server %Hostname% and connect to port 3389 on that side. For the SSH connection, use port 22 and go to IP address %IP%.”
Remember that the values for %Hostname% and %IP% will be filled in based off what the user picks. Putty will also launch in a separate window, not so obviously. At this point, the user can minimize the batch file, as it will remain open as long as the SSH session is in progress. Switch to the PuTTY window, and log in with your username and password.
If you actually try to use this, you’ll have to connect Remote Desktop by typing in localhost:9001 to the computer field of the Remote Desktop Window after the SSH session is established. Remember we told PuTTY to Listen on 9001, and send anything that connects to it to the Hostname on the other side to port 3389.
You can use the same techniques we already discussed to use a VNC client instead of Remote Desktop and change the application launched with “start” and the port that putty connects to on the other side. Or, even cooler make variables and allow the user to decide on RDP or VNC.
Lastly as cleanup, we include the finishing up bit.
echo Shutting down connection
:END
Once the user ends the connection we’ll send this message, again that will probably flash by so fast the user won’t see it unless you slow it down with the handy ping command you learned already. Lastly, we have the :END label to jump to anytime the user hit’s Q or q.
Don’t forget at the end to save your file with a .bat extension (not ssh.bat.txt, but ssh.bat). It’s icon will look like a gear in a box if you did it right. Double click on it to run it.
I’m sure you’ll have to play with this to get it to work, and I may not have explained it as well as I could have, but you are a Gorilla Admin. Use your brain, and get it to work, and make me proud.