Friday, September 01, 2006

Execute a Command Only If Connected To Internet

You may want to execute a (scheduled) command or a program only if your computer is connected to the Internet or if a specific server is online. You can do this with a simple batch file...

@echo off

ping www.mysite.com /n 1| find "time="
if errorlevel 1 goto nonet

my_command_here
goto done

:nonet
echo No network connection detected to my server, aborted.

:done

I think that the code is self explanatory, but... First we ping the server and check if it is online and show a message if not. Then we carry out the operation and exit.
This type of batch file is ideal for scheduled jobs like scheduled updates or backups. You can also redirect the result of your job to a log file.
For example, here is a batch file that will manually update the virus definitions for F-Secure Internet Security 2006 and logs the result (it works, but it is just for demo purposes because it has a better, built-in, auto update feature):

@echo off

echo Scheduled update started %date% %time%... > log.txt
echo. >> log.txt

ping ftp.f-secure.com /n 1| find "time="
if errorlevel 1 goto nonet

ftp -i -n -s:ftp_commands.txt -w:102400 -A ftp.f-secure.com >> log.txt
fsupdate /s
echo Update finished, exit code %errorlevel%.
del fsupdate.exe
goto done

:nonet
echo No connection to ftp.f-secure.com, update aborted. >> log.txt

:done

You will also need a file called ftp_commands.txt in the same folder as the batch file with the following content:

cd /anti-virus/updates/
bin
get fsupdate.exe
quit

This file is used to send commands to the ftp utility so it will fetch the file fsupdate.exe automatically for you.

No comments: