DanEng
DanEng

Reputation: 428

Wait for network connection before executing a batch file

I have a bat to run a python script when logging on Windows.

start C:\python34\pythonw.exe D:\myscript.py

The myscript.py requires some Internet activities, and sometimes it can't be executed properly because the internet connection has not been activated immediately after logging on Windows.

How to make sure myscript runs only after the Internet connection has established?

Upvotes: 1

Views: 6668

Answers (3)

Mani R
Mani R

Reputation: 40

This is working for me, may it will help to you also!


@ECHO OFF
:loop
PING google.com | FIND "time=" > NUL
echo waiting.....
IF ERRORLEVEL 1 goto loop 

ECHO You have active connection to the Internet

REM you can add your scripts to run after internet connection success

pause

Now I am trying to show as the loading in bat, the above code will print waiting.... until the connection is a success

Upvotes: 0

err
err

Reputation: 1

@echo off
set target=www.google.com
echo Waiting for connection..
:ping
<nul set /p strTemp=.
timeout 2 > NUL
ping %target% -n 1 | find "TTL="
if errorlevel==1 goto ping
echo.
echo Connected
REM start somthing
REM start C:\_soft\putty.exe

Upvotes: 0

Script_Coded
Script_Coded

Reputation: 710

Just ping a server such as www.google.com Then you just have to check the answer with errorlevel like this:

ping www.google.com -n 1 -w 1000
if errorlevel 0 start C:\python34\pythonw.exe D:\myscript.py
if errorlevel 1 echo No network

EDIT: Added a couple lines of code.

YET ANOTHER EDIT: A much better way of doing it would be like this:

:ping
ping 1.2.3.4 -n 1 -w 1000 > nul
set target=www.google.com
ping %target% -n 1 | find "TTL="
if errorlevel==1 goto ping
start C:\python34\pythonw.exe D:\myscript.py

The first ping is there to add a 1 sec (1000 millisec) delay so we don't overload.

Upvotes: 4

Related Questions