Restart server based on ping response - loops

I've created this from a mashup of other questions/answers on this site, as well as stuff found at ss64.com
I've hammered it down to what I want, now it's just a crucial missing detail that will make it loop over and over until the connection has been established while avoiding constantly starting the server on each cycle.
It's massively over-engineered and horrendously made, but it's basically the culmination of all I've learned and just working it out in a way I can understand.
The main issue with it right now is if it's less than 100% packet loss, it will start the server, even if it's 80% packet loss which is too high for anything to connect or function on.
I'm looking for that crucial command to ensure the server will only start if there is 100% connection and also make sure it wont keep starting the server if there is 100% connection in a continued loop (which has happened far too many times, 50 instances of a server running really is a PC killer).
Here is what I have (don't laugh too hard).
#echo off
title Server Restart
color 0A
cls
:start
Cls
set ip=xxx.xx.xxx.xx
:ping
ping %ip% -n 5 || goto PingFail
timeout /t 8
cls
echo Ping was Successful to %ip% at %date% %time%
timeout /t 10
ping %ip% -n 5 -w 5000 && goto start
echo Moving To PingFail...
goto PingFail
:Starting
Echo Connection Established... Starting server
**Start Server.bat**
Echo Start Successful
goto start
:PingFail
cls
Echo Connection Has Failed.. looping.
timeout /t 3
goto Pingloop
:Pingloop
echo PINGLOOPING
ping %ip% -n 5 || goto Pingloop
timeout /t 15
goto Starting

What kind of servers are we talking about? And you are aware that most firewalls block ping request by default right?
You can use: https://uptimerobot.com/ and use their API to get valid information.
If you want to be sure you that you have a connection to the outside world you can check for 0% loss like this:
ping -n 1 -4 www.google.com | grep "0% loss"
I have never seen 80% or 60% loss but of course you can change 0% to whatever percentage. Though pinging your own public IP doesn't mean you have a working internet connection. You need to ping the 'world' not your home.

Related

timeout /t 10 /nobreak > NUL is getting stuck and not coming out to execute next statement on windows 2003 server VM

"timeout /t 10 /nobreak > NUL" is getting stuck and not coming out to execute the next statement.
I have written a below script which executes as expected on my dev machine and also tested on few test machines also. it waits for 10 seconds and the again start execution (tested in safe mode also), but on one of the machine windows 2003 server which license is expired my script runs in safe mode, but when executing the above timeout statement it doesn't execute the next statement.
Can someone please tell me the reason if any and what will be the solution?
set restart=1
...
... some other code
...
setlocal ENABLEDELAYEDEXPANSION
:WaitToRestart
if "%restart%"=="1" (
echo waiting for restart >> log.txt
shutdown /r /t 0
if "!errorlevel!" NEQ "0" (
echo error: !errorlevel! while restarting so wait for 10 sec >> log.txt
timeout /t 10 /nobreak > NUL
goto WaitToRestart
)
echo error: !errorlevel! you shuld not be here to see after death >> log.txt
)
setlocal DisableDelayedExpansion
On my dev machine, this script runs well (windows 10) but stuck on the production environment (where it runs as a startup script which run after boot in safe mode) on Windows 2003.
So I change the "timeout" command with command "PING localhost -n 6 >NUL" but it also stuck after rotating 10, 12 times. And when I removed "PING" command also then it rotates for a long time till the command "shutdown" executed successfully.
It looks like the machine-specific issue and maybe stopped because of license expire issue as the I have created VM from backup of physical machine
If you're just trying to get a wait function, you can manipulate ping to do that.
ping 0 -w 1000 -n 10 >nul
Breaking this apart piece by piece, cmd expands 0 to 0.0.0.0, which is the IP address cmd will try to ping (it doesn't exist). -w specifies the number of milliseconds ping will wait before timing out a request. -n specifies how many requests you'd like to send (so your total duration, in seconds is w/1000 * n). >nul is not ping-specific; it nullifies the output to the console.
By pinging an IP that doesn't exist, you force ping to timeout with every request, which gets you a dependable wait time.

batch file timeout command jumping to 10k, 30k, 40k seconds

I'm currently running a set of commands that utilizes the timeout function in my batch files. The timeout function uses a variable for how many seconds it should pause, and I think that may be causing issues, but I desperately need it to function properly.
I've got an update to my question which details more about what may be happening.
I used some suggestions that I had in the comments to try and fix my script, but it did not work.
Here is my script:
:connectToTheInternet
setlocal EnableDelayedExpansion
set timeout=2
echo checking internet connection
echo.
:connectToTheInternetRestart
ping -n 1 google.com | find /i "TTL=" >NUL && (
echo Internet connection already established, checking script versions.
echo.
goto scriptVersion
REM toupd
) || (
if "%COUNTER%"=="0" (
echo Creating wifi profile.
echo.
set /A COUNTER=1
goto createWifiProfile
)
SET /A "tries = (%COUNTER%-1)+1"
REM if failed endonfail times, give up
if "%COUNTER%"=="%endonfail%" (
echo Error: Could not connect to network %tries% times, stopping script.
echo.
goto endNoShutdown
)
echo.
echo Attempt #%COUNTER%.
echo.
REM raise waiting time between connections
SET /A "modulo = (%COUNTER%-1) %% 2"
if "%modulo%" EQU "0" (
set /A timeout=timeout+2
echo failed %tries% times in a row. Increasing wait time between actions to %timeout% seconds.
set /A COUNTER=COUNTER+1
) else (
set /A COUNTER=COUNTER+1
)
REM disconnect existing network
netsh wlan disconnect
netsh wlan delete profile name="%wifissid%"
timeout /t 1 /nobreak
echo.
REM attempt connection
netsh wlan add profile filename="connect.xml"
netsh wlan connect name="%wifissid%" ssid="%wifissid%" >NUL
echo.
echo Wait time is currently !timeout! seconds.
timeout /t !timeout! /nobreak
echo.
REM check pings
ping -n 1 google.com | find /i "TTL=" >NUL && (
echo Successfully connected. Checking script version.
echo.
goto scriptVersion
) || (
set /a COUNTER2=COUNTER+1
echo Connection attempt failed. Starting attempt #%COUNTER2% in 3 seconds.
echo.
timeout /t 3 /nobreak
cls
goto connectToTheInternetRestart
)
)
My problem is specifically the timeout /t !timeout! /nobreak which should wait for a variabled amount of time. The problem is, sometimes (it only happens when the device successfully connects to the internet, but not every time the device connects to the internet) the timeout jumps up to 10,000 seconds, 30,000 seconds or some other random high number (And they really are random, I've seen some at like 12,536 seconds.) When it should always be less than 12 based on the timeout variable. Yes, I mean seconds NOT milliseconds. As you can imagine, there is a big difference between 10k seconds (roughly 21 days) vs 10 seconds.
I have no idea what could be causing this, or how to solve it and would love some help.
Here's a left-field thought, brought about by your comment
(it only happens when the device successfully connects to the internet, but not every time the device connects to the internet)
Before it connects to the internet, is the date, time and timezone correct? Connecting will synchronise the time - which may muck up your timeouts!
Like I said: left-field, but...
choice seems not to be affected by the mentioned behaviour of timeout: "when changing the time from another cmd window while running a timeout 300, the "waiting for ..." prompt indeed changes the remaining time accordingly".
So instead of timeout /t !timeout! you can use
choice /n /c yn /d y /t !timeout!
/c yn is just for making it language independent.

Glitch when running homemade script CMD

I have been dinking around with batch files, and decided to have a little bit of fun creating a command usable in the command line "Hack", which looks like it will make it look like something bad is happening, but nothing really is. Here is the source for that:
#echo off
ECHO Parsing Buffer Strings...
Delay 3000
ECHO Reading Args from FTP Protocol...
Delay 3000
ECHO Interpreting BAUD rate...
Delay 3000
ECHO Reading IBM Standards...
Delay 3000
ECHO Removing Multiplexer matrices...
Delay 3000
ECHO Compiling zip files...
Delay 3000
ECHO Complete. System OS bypassed.
PAUSE
Now, as you may have noticed, there is no built-in "Delay" command, so I made one myself, placing the newly made Batch file in System32 along with Hack.bat:
#echo off
ping 1.1.1.1 -n 1 -w %1 > nul
This takes in one parameter, the amount of delay (ms), and pings a non-existent computer. It tries once to ping it, waiting %1 ms before it gives up. Now, when I put it the command "Hack", it says "Parsing buffer strings", waits three seconds, then the script stops. Now, when I turned echo on to see what the problem was, it said "Parsing buffer strings\nDelay 3000", waited three seconds, then the script stopped. Why? Thank you.
where is your procedure definition and it's call ? you shoud have done someting like :
echo parsing ...
call :delay 3000
echo reading ...
call :delay 3000
exit
:delay
ping 1.1.1.1 -n 1 -w %1 > nul
ping addr -n 1 -w 3000 will only work as long as addr is unreachable. When for some reason the address becomes reachable, the command will return immediately. It will also pollute the network (just a little, but still).
If you don't need millisecond delays, a better approach would be something like this:
#echo off
echo %TIME%
call :delay 5
echo %TIME%
goto :eof
:delay
set /a count=%1+1
ping -n %count% 127.0.0.1 >nul
Output:
C:\>delay.cmd
12:47:44,33
12:47:49,38
ping has a delay of roughly 1 second between two echo requests, so you can sleep for n seconds by sending n+1 echo requests to localhost.

Pause a batch file until a host is reachable (using ping)?

I'm looking to add some functionality to a batch file that I've been writing;
essentially what happens is I dial up a VPN connection using openvpn and then continue to mount a network drive as well as many other things, what I'm looking to do is:
Dial the connection via OpenVPN (which I have working fine)
Ping a host on the other side of the VPN and don't continue through the batch file until this host is reachable.
Currently I've been using a sleep command of 20 seconds which works, but is not a very clean or intelligent way of going about it; I'd imagine I need some sort of loop to attempt to ping the host infinitely until it is reachable before continuing in the batch file. Any help would be greatly appreciated.
from antoher thread on stackoverflow... credit to paxdiablo (find the original post here)
#setlocal enableextensions enabledelayedexpansion
#echo off
set ipaddr=%1
:loop
set state=down
for /f "tokens=5,7" %%a in ('ping -n 1 !ipaddr!') do (
if "x%%a"=="xReceived" if "x%%b"=="x1," set state=up
)
echo.Link is !state!
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal
This will give you enough ammo to use and solve your problem
as already mentioned years ago, output of ping is language dependent, so it's not a good idea to rely on a string like Received. The preferred and most reliable method is searching for the string TTL=:
:loop
timeout 2
ping -n 1 %ipaddress% |find "TTL=" || goto :loop
echo Answer received.
|| works as "if previous command (find) wasn't successful, then"
(as for the timeout: never build a loop without some idle time to reduce CPU load)
It works if You translate the "Received" string using the string that your language uses for the word Received (i.e. in Italian is Ricevuti).

Batch file - Display text for 5 seconds

How can I display my data from x.bat for 5 seconds?
When this code runs, it's impossible for me to see anything, it opens and closes immediately.
#ECHO OFF
:BEGIN
ECHO Authorized user
:END
If I use pause, the user still needs to hit a key to close the screen, that's why this should happen automatically.
#ECHO OFF
:BEGIN
ECHO Authorized user
pause
:END
Thanks
#ECHO OFF
:BEGIN
ECHO Authorized user
timeout 5 >nul
cls
:END
You can grab "sleep.exe" from the Windows Server 2003 resource kit and use sleep [seconds] but the easiest way to get a set delay is to simply ping localhost N+1 times, where N is the number of seconds.
This will sleep for five seconds (there's no delay before the first ping, and a 1s delay after each):
ping -n 6 localhost>nul
SLEEP 5
GOTO:EOF
Would wait for 5 seconds before closing the window.
On Windows Vista and later you can use timeout:
timeout 5 >nul
On ancient Windows versions you need to resort to ping:
ping -n 6 localhost >nul 2>&1
An alternative way to use ping, which also seems to be slightly less precise:
ping -n 1 -w 5000 1.0.0.0 >null
That is, convert seconds to milliseconds and use that as an argument of -w parameter. The -n parameter should have the argument of 1. The host should be a knowingly inaccessible IP address.
variety of ways to resolve this
timeout /t 5 /nobreak >Nul
::for 5 sec
#PING 1.1.1.1 -n 2 -w 3000>nul
:: -n 2 for around 5-6 seconds
sleep 5 (EMERGENCY CASE)

Resources