python - how to get an on wifi access event code example

Example: python - how to get an on wifi access event

import socket
import time
import subprocess

def check():#this function checks if there is an wifi access
    try:
        host = socket.gethostbyname("www.google.com")
        s = socket.create_connection((host, 80), 2)
        return True
    except Exception:
        return False

      
while True:#if you want to do something when you get a wifi access so use this loop
    if check() == True:
        DoSomeStuff()#whatever you want to do
    else:
        subprocess.call(["/bin/bash", "-c", "rfkill", "block", "wifi"])
        subprocess.call(["/bin/bash", "-c", "rfkill", "unblock", "wifi"])
        subprocess.Popen(["/bin/bash", "-c", "notify-send 'conncection re-established'"])
    time.sleep(4)

Tags:

Misc Example