Script to check tunnel status periodically on Windows

This post is delayed for more than 10 months because I forgot about it. Sorry about that.

To improve the availability of the reverse-tunnel, we would check up the status periodically via Scheduled Tasks. Now, we need to write a batch script and add it into Windows.

First, the script I wrote:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@ECHO OFF

SET _SERVER={Server ip}
SET _PORT={Server port}

SET _SERVICE={Your service name installed in Windows}

:TUNNEL_CHECK
start /MIN /B netstat.exe -nav -p TCP | FIND /C "%_SERVER%:%_PORT%" | FIND "1" > nul 2>&1
IF ERRORLEVEL 1 CALL :TUNNEL_RESTART
EXIT /B

:TUNNEL_RESTART
start /MIN /B net stop %_SERVICE%
start /MIN /B net start %_SERVICE%

Actually, I’m a newbie of batch script in Windows and the script may be ugly. The script first defined some variables we will use later: the destination server’s ip and port, and the service name we installed in Windows.

The main function is TUNNEL_CHECK. We start a command without creating a new window (/B) or minimizing it (/MIN). For netstat.exe, we list all active connections numerically (-an) and filtered with TCP only (-p TCP). Then we count the lines (/C) matched to our server string by FIND. We will restart the service if there is error exist. Otherwise, exit the program.

Second, we shall add this script into Windows. Open the the configure window via: Start > All Programs > Accessories > System Tools > Scheduled Tasks. Then create a new task with the script. I’ll list the settings when editing the task.

In the Schedule tab of the task, we need two schedules. One is Run at system startup and another one is ran periodically: In my settings, the script is a Repeat task for every 1 hour and its duration is 23 hours. The tasks itself is Scheduled as Daily from 12:00 AM every 1 Day.

Generally speaking, this script will run at system start-up, and every hour of every day. To avoid any problem, I uncheck all boxes in the Settings tab. Another note is to set up the task ran as a valid user. This step will make it run at system start-up successfully. If the user is password-protected, we shall also set the password.

It’s all the details of my checking script. Enjoy it. 🙂

Leave a Reply

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