make a batch script foward an IP - windows

Hi so my coworker requested if I could make a script. I am sure what I want it to do and wrote some pseudo code in bash style now of course this not useable for him since he is on Windows. So I tried to implement in a .bat script now here is where my knowledge comes a bit short. What I need the script to do is to connect to a certain VPN-ip if that is not avaible the localsystem should foward it to another VPN so he doesn't need to worry about it. Either one of 2 should always be reachable. But they are never at the same time. This is for test tooling.
Pseudo bashcode
while true
do
From local if
10.10.1.15 avaible connect to it
else
10.168.84.47 connect to it
elseif
try to connect to 10.10.1.15 again && verify that'
else
echo 'error device over VPN unavaible'
My Attempted batch script, I am pretty sure that what I have now is not gonna work
#setlocal enableextensions enabledelayedexpansion
#echo off
set ipaddr=%1
:loop
set state=down
for /f "tokens=5,6,7" %%a in ('ping -n 1 !ipaddr!') do (
if "x%%b"=="xunreachable." goto :endloop
if "x%%a"=="xReceived" if "x%%c"=="x1," set state=up
)
:endloop
echo.Link is !state!
ping -n 6 10.10.1.15 >nul: 2>nul:
goto :loop
endlocal
IF EXIST 10.10.1.15 (
is reacheable connect
) ELSE (
netsh interface portproxy add v4tov4 listenport=80 connectaddress=10.10.1.15 fowardaddress=10.168.84.47
)

So far as I know, you can just try to find "ttl=" to determine success/fail for a ping without worrying about all those tokens and different versions of cmd. I'm sure someone will correct me if I'm wrong.
untested
set ip=127.0.0.1
rem 2 pings waiting 900ms for a reply
ping -n 2 -w 900 %ip%|find /i "ttl=">nul || goto :fail
rem If we get here then the ping succeeded
rem do what you want here
goto :eof
:fail
rem If we get here then the ping failed.
rem do what you want here
goto :eof
The || operator basically means "if the previous command fails then do this".

Related

Why I'm not being able to declare a variable inside a 'if exist' syntax in Batch (Windows) file?

In the following script few things won't work right and i'm having a hard time trying to figure the why, First it gives a 'Null' value to the variable (The .txt file is not empty), second it returns to me that some funcitons are not expected at that moment (Such as'goto' was not expected) so it maybe something with the syntax?
#echo off
set name1=sample1
set name2=sample2
set name3=sample3
set ccount=0
del mes.txt
:WFC
ping localhost -n 2 >nul
if exist mes.txt (
SetLocal EnableDelayedExpansion
set /p cname=<mes.txt
set /a ccount=%ccount%+1
if %cname%==!name%ccount%! goto AllowedList
if %ccount%==20 goto Crasher
goto WFC
I tryed calling echo %cname% in the end of the script and appareantly the var have a "nil" value, plus I also turned the #echo on and haven't found nothing useful to understand the problem.
The weirdest part is that if I take the variable declaration out of the 'if exist statemant', the whole script it works marvelously as in:
#echo off
set name1=sample1
set name2=sample2
set name3=sample3
set ccount=0
del mes.txt
:WFC
ping localhost -n 2 >nul
set /p cname=<mes.txt
if exist mes.txt (
SetLocal EnableDelayedExpansion
set /a ccount=%ccount%+1
if %cname%==!name%ccount%! goto AllowedList
if %ccount%==20 goto Crasher
goto WFC
So, this could be satisfying enough but it's not, there's a second software updating the mes.txt value all the time and I'm assuming that there will be some(not much, but some) cases in the second script where the var cname will get null value and still it will compare a null value with name1, completing excluding sample1 of the allowed lists. Can anyone solve this problem or at least explain the why?
Thankfully to the user MC ND, who awnsered me in the comments, I've managed to solve it, turns out that it was a really simple thing, his awnser was:
Your problem is delayed expansion (the lack of it) when reading %cname% and %ccount% (read here) – MC ND 24 mins ago
What I did to the script to make it work was:
#echo off
set name1=sample1
set name2=sample2
set name3=sample3
set ccount=0
del mes.txt
:WFC
ping localhost -n 2 >nul
set /p cname=<mes.txt
if exist mes.txt (
SetLocal EnableDelayedExpansion
set /a ccount=%ccount%+1
if !cname!==!name%ccount%! goto AllowedList
if !ccount!==20 goto Crasher
goto WFC
My guess is that it should be something more like this
:WFC
Timeout 1 1>Nul
If Not Exist mes.txt GoTo :WFC
SetLocal EnableDelayedExpansion
Set/P cname=<mes.txt
Set/A ccount+=1
If %ccount% Equ 20 GoTo :Crasher
If "!name%ccount%!" Equ "%cname%" GoTo :AllowedList
GoTo :WFC

Computer script for auto-reboot on network loss

I am working with a IP Camera network and need a script to run on each individual PC that will perform an auto-reboot when network loss happens. I would like to be able to have the PC ping the servers IP every 5 minutes and upon loss of connectivity the PC will reboot. Each PC has a Camera viewer but periodically looses network connection with the NVR. I found almost the same issue/solution here: http://www.cam-it.org/index.php?topic=2786.0
However the script provided didn't work for me. Below is the script I found and tried but didn't function the way I needed.
#Echo off
REM Put REM in front of Echo off to view the file output
REM ---------------------------------------------------------
REM WATCHDOG.CMD
REM Restarts PC after 3 unsuccessful attempts to PING the
REM POE switch
REM --------------------------------------------------------
SET COUNT=C:\Temp\WATCHDOG.txt
SET POESWITCH=192.168.1.253
SET ERRFLG=0
IF EXIST "%COUNT%" (
SET /P ERRFLG= <%COUNT%
)
IF %ERRFLG% GTR 2 (
Echo Restarting PC in 60 seconds. Run SHUTDOWN -a to abort.
DEL %COUNT%
SHUTDOWN -r -t 60 -f
GOTO :EOF
)
PING -n 1 %POESWITCH%|findstr /I /C:"timed out" /C:"unreachable" /C:"general failure"
if %ERRORLEVEL% == 1 Goto Done
SET /a ERRFLG +=1
ECHO %ERRFLG% > %COUNT%
:Done
(http://www.cam-it.org/index.php?topic=2786.0)
Any suggestions would be greatly appreciated.
Thanks,
Jordan
Add the reboot command and it should work for you to test a URL/IP address every 300 seconds
#echo off
set ip=www.google.com
:loop
ping -n 2 %ip% |find "TTL=" >nul || echo reboot command here
ping -n 300 localhost >nul
goto :loop

How to retrieve ping data through a command line?

Is it possible to retrieve the data output when you type ping in the command line?
Currently, we have existing servers that we check daily by typing ping (IP address) in the command line but only during at the start of the day. We would only be notified if the server is down once the user notifies us. The manual thing to do is to do a continuous ping and do a timely check of whether it was disconnected or not.
I would like to create something that would give out a prompt (while doing a continuous ping in the background) once the command line declares that there's a "request time out", intermittent connection, etc. So that there wouldn't be a need to manually check the status of the connection.
I realize this was asked 2 months ago, but it was never answered. Hopefully this will still be useful to someone. Granted, it's much easier to implement using a "real" programming language, but sometimes you need something that uses only built-in commands.
Configure as needed via environment variables (examples shown). To be polite, you probably want to use much longer timeouts if you don't own the server you're pinging.
#echo off
cls
setlocal enabledelayedexpansion
REM Configuration:
set SERVER=google.com
set TIMEOUT_AFTER_PING_FAIL_SECONDS=5
set TIMEOUT_AFTER_PING_SUCCEED_SECONDS=10
set TIMEOUT_AFTER_LINK_DOWN_SECONDS=15
set DECLARE_LINK_DOWN_FAILS=5
set CONSECUTIVE_FAIL_COUNT=0
:Start
set PING_RESULT=Failure
for /f "delims=" %%X in ('ping /n 1 %SERVER%') do (
set TEMPVAR=%%X
if "Reply from"=="!TEMPVAR:~0,10!" set PING_RESULT=Success
)
goto:!PING_RESULT!
:Success
echo Ping Succeeded
set CONSECUTIVE_FAIL_COUNT=0
call:Sleep %TIMEOUT_AFTER_PING_SUCCEED_SECONDS%
goto:Start
:Failure
set /A CONSECUTIVE_FAIL_COUNT+=1
echo Ping Failed !CONSECUTIVE_FAIL_COUNT! Time(s)
if !CONSECUTIVE_FAIL_COUNT!==%DECLARE_LINK_DOWN_FAILS% (call:LinkDownHandler&goto:Start)
call:Sleep %TIMEOUT_AFTER_PING_FAIL_SECONDS%
goto:Start
:Sleep
REM See http://stackoverflow.com/questions/4317020/windows-batch-sleep
setlocal
set /A ITERATIONS=%1+1
ping -n %ITERATIONS% 127.0.0.1 >nul
goto:eof
:LinkDownHandler
echo Link is Down
set CONSECUTIVE_FAIL_COUNT=0
REM Add additional link-down handler actions here
call:Sleep %TIMEOUT_AFTER_LINK_DOWN_SECONDS%
goto:eof

Test for internet intermittency

I was wondering if there is a way to write a cmd script or something for Windows that will allow me to tell when my internet connection has severed.
In Ubuntu, I would have written a shell script to ping Google once per second and if it is impossible record the time etc etc.
Is it possible to do a similar thing in Windows?
There may be a better way to monitor the connection status. But here is a Windows batch implementation of the logic you specified.
#echo off
setlocal enableDelayedExpansion
set log="internetStatus.txt"
set "status="
>>%log% echo %date% %time%: Begin monitoring
for /l %%A in () do (
>nul ping -n 2 -w 1000 google.com && (
if "%status%"=="FAIL" (
>>%log% echo %date% %time%: internet connection succeeded
set "status=OK"
)
) || (
if "%status%"=="OK" (
>>%log% echo %date% %time%: Internet connection to google.com failed
set "status=FAIL"
)
)
)

Batch file add/remove hosts file entries syntax error

The following script is supposed to manage adding and removing entries into the hosts file. Entries with .dev are supposed to point to localhost and all others should prompt for an IP address. If the entry already exists it should ask you if you want to remove it.
I am getting a vague The syntax of the command is incorrect error but I'm not sure which line it's referring to. If I turn #echo on it then spits out if ( on the next line and then dies. The only way I can catch the error is to do a screenshot because it immediately exits.
I've spent several hours on this, so any assistance would be greatly appreciated!
#echo off
title ClearSight Studio
echo Virtual website setup script
echo Version 1.4
echo Last modified 12/30/2011
echo.
REM Get the name of the domain name
echo What domain name? Ctrl+C to cancel. Example: newdomain.dev.
set /p domain= Domain:
REM Set a variable for the Windows hosts file location
set hostpath=\windows\system32\drivers\etc
set hostfile=hosts
set sitespath=\clearsight\sites
set extension=%domain:~-3%
REM Make the hosts file writable
attrib -r %hostpath%\%hostfile%
REM Add the domain to point to localhost at the end of the file if it doesn't already have an entry.
find /c " %domain%" %hostpath%\%hostfile%
if errorlevel 1 (
if /i %extension%==dev (
set /p ip= What is the IP?
)
echo. >> %hostpath%\%hostfile%
echo.# Adding %domain% via batch process on %date:~10,4%-%date:~4,2%-%date:~7,2%. >> %hostpath%\%hostfile%
if %ip% (
echo.%ip% %domain% >> %hostpath%\%hostfile%
) else (
echo.127.0.0.1 %domain% >> %hostpath%\%hostfile%
)
) else if errorlevel 0 (
echo Entry found in hostfile already. Would you like to remove it?
set /p remove= Remove (Y/N)
if /i %remove%==Y (
findstr /v "%domain%" %hostpath%\%hostfile% > %hostpath%\%hostfile%
)
)
if /i %extension%==dev (
REM Create the folder if it doesn't exist
if exist %sitespath%\%domain% (
echo %sitespath%\%domain% already exists.
) else (
echo Creating %sitespath%\%domain%...
mkdir %sitespath%\%domain%
)
)
REM Clean up
attrib +r %hostpath%\%hostfile%
echo.
echo Done.
if /i %extension%==dev (
REM Do a "git" of the repo, if requested
echo Would you like to clone an external git repository named %domain% from Bitbucket?
echo This assumes the git repository was set up under the "jamonholmgren" account.
echo Do it manually if it's under someone else's account. Also, make sure you have permissions to this repo.
set /p getgit= Get git clone? (Y/N):
)
REM
if /i %getgit%==Y (
git clone git#bitbucket.org:jamonholmgren/%domain%.git %sitespath%\%domain%\
pause
) else (
echo Okay, then we're done.
pause
)
You have two problems with this bit of code
if %ip% (
echo.%ip% %domain% >> %hostpath%\%hostfile%
) else (
It is invalid syntax. I presume you want to test if the variable is defined. The proper syntax is if defined ip (
You are attempting to expand %ip% in the same if() block where it was defined. This can't work because %ip% is expanded at parse time, which is before you assign the value! The solution is to use delayed expansion instead !ip!. Delayed expansion must first be enabled, probably near the top of your script, using setlocal enableDelayedExpansion
So the fixed code would look something like this
setlocal enableDelayedExpansion
.
.
.
if defined ip (
echo.!ip! %domain% >> %hostpath%\%hostfile%
) else (
You have the same delayed expansion issue with %remove%
Edit - expanding on Andriy M's comment
You also have a potential issue with how you deal with user input for ip and remove. Both values should be initialized either to nothing, or to a default value, prior to prompting for the value. If the user does not enter anything, then the existing default value (if any) is preserved.
Also, you may want to confirm that a valid value was entered, especially for the ip. If you do, then you will want to take the prompt out of the loop and put it in a called subroutine. The subroutine can check if a value was entered and loop back to try again if it wasn't. It must be in a subroutine because you cannot GOTO within a parenthesized block of code like you have with your IF statement.
When you expand a variable value via %variable% its value is expanded just once after the line that contain commands is read and before the commands are executed. For example:
set var=Original
set var=New & echo %var%
Previous line show "Original". The same effect happen with any command enclosed in parentheses (that belong to any IF or FOR commands).
The way to solve this problem is using Delayed Variable Expansion by enclosing a variable in exclamation marks instead percents:
set var=Original
set var=New & echo !var!
However, you must first activate the delayed expansion with this command:
setlocal EnableDelayedExpansion
So, insert previous line at beginning of your program and change ALL references to variables that may change its value inside an IF or FOR by !name! instead of %name%. For example:
if %ip% (
that I'm sure is the line that caused your problem...
Thanks everyone for the help! Here is the final (working) result in case anyone ever wants to do something similar. The output to the screen could probably use a little tweaking but in all my testing it seems completely reliable.
#echo off
setlocal enableDelayedExpansion
title ClearSight Studio
echo Virtual website setup script
echo Version 1.5
echo Last modified 2/23/2012
echo.
REM Get the name of the domain name
echo What domain name? Ctrl+C to cancel. Example: newdomain.dev.
set /p domain= Domain:
REM Set a variable for the Windows hosts file location
set hostpath=\windows\system32\drivers\etc
set hostfile=hosts
set sitespath=\clearsight\sites
set extension=%domain:~-3%
REM Make the hosts file writable
attrib -r %hostpath%\%hostfile%
REM Add the domain to point to localhost at the end of the file if it doesn't already have an entry.
find /c " %domain%" %hostpath%\%hostfile%
if errorlevel 1 (
if /i NOT %extension%==dev (
set /p ip= What is the IP?
) else (
set ip=127.0.0.1
)
echo. >> %hostpath%\%hostfile%
echo.# Adding %domain% via batch process on %date:~10,4%-%date:~4,2%-%date:~7,2%. >> %hostpath%\%hostfile%
echo.!ip! %domain% >> %hostpath%\%hostfile%
) else if errorlevel 0 (
echo Entry found in hostfile already.
set /p remove= Would you like to remove it? (Y/N)
if /i !remove!==Y (
findstr /v %domain% %hostpath%\%hostfile% > %hostpath%\%hostfile%.txt
type %hostpath%\%hostfile%.txt > %hostpath%\%hostfile%
)
)
if /i %extension%==dev (
REM Create the folder if it doesn't exist
if exist %sitespath%\%domain% (
echo %sitespath%\%domain% already exists.
) else (
echo Creating %sitespath%\%domain%...
mkdir %sitespath%\%domain%
)
)
REM Clean up
attrib +r %hostpath%\%hostfile%
REM Flush DNS so the changes are available imidiately
ipconfig /flushdns
echo.
echo Done.
if /i %extension%==dev (
REM Do a "git" of the repo, if requested
echo Would you like to clone an external git repository named %domain% from Bitbucket?
echo This assumes the git repository was set up under the "jamonholmgren" account.
echo Do it manually if it's under someone else's account. Also, make sure you have permissions to this repo.
set /p getgit= Get git clone? (Y/N)
)
REM
if /i !getgit!==Y (
git clone git#bitbucket.org:jamonholmgren/%domain%.git %sitespath%\%domain%\
pause
) else (
echo Okay, then we're done.
pause
)
Just some hints for debugging the batch file:
Start it from a cmd shell to avoid closing the window after exiting
Add more REM commands that will serve as log entries when turning echo on
Simplify your script by repeatedly removing parts from the end until it runs without error. Reinsert the faulty parts and try to figure out what's wrong there
While this does not quite answer your question, I hope the hints will help you solve the problem. You are always welcome to ask for general advice, but I'm afraid that your particular problem is somehow a bit too specific to be of general interest.

Resources