bcsta
bcsta

Reputation: 2307

Python keep pinging host until reachable. First time not reachable print on console

I am using python's os.system to ping a website.

from os import system
system('ping www.stackoverflow.com')

This gives the below result:

64 bytes from 151.101.1.69: icmp_seq=0 ttl=117 time=102.540 ms
64 bytes from 151.101.1.69: icmp_seq=1 ttl=117 time=101.990 ms
64 bytes from 151.101.1.69: icmp_seq=2 ttl=117 time=101.690 ms
64 bytes from 151.101.1.69: icmp_seq=3 ttl=117 time=106.207 ms
64 bytes from 151.101.1.69: icmp_seq=4 ttl=117 time=118.015 ms
...

I would like, however, to stop the bing once the website is reached and continue pinging if not reached.

system('ping -c 1 www.stackoverflow.com')

This will only ping once which is not what I want. How can I achieve what I want?

I would also like to print on the console a message the first time the website was unreachable. How is this achieved?

Upvotes: 0

Views: 1399

Answers (1)

urban
urban

Reputation: 5682

I would use subprocess module since you have more control.

An example implementation of a function that will only return if the site is up while it will keep on pinging if the site is down:


import subprocess
import time

def ping_until_up(site="www.stackoverflow.com"):
    while True:
        status = subprocess.run(["ping", "-c", "3", site], capture_output=True)
        if status.returncode == 0:
            return
        print("Site is down...")
        time.sleep(30)


# -- Test --
import sys
ping_until_up(sys.argv[1])

This gives you:

$ python3 ./test.py www.google.com
$ python3 ./test.py asd.asd.asd
Site is down...
Site is down...
Site is down...
...

Few things to note:

  • I do 3 pings since 1 might lead to false negatives
  • You should probably handle different types of errors. In the above example is actually a DNS error. You can do this with the captured output
  • This function sleeps 30 secs between attempts and prints in every failed round but you can easily change that behaviour to fit your case

Upvotes: 2

Related Questions