BaSs_HaXoR

wifi auto on-connect script #1/2 (for windows wifi)

Nov 18th, 2025 (edited)
2,408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.91 KB | None | 0 0
  1. #############################################################################################################
  2. # AUTORUN WIFI CONNECT when disconnected IMMEDIATELY after disconnect, and every 30 seconds thereafter.
  3. # This project is used (for me personally) for RDP access on a LAN PC RIG. Using this script, i can make sure
  4. # my wifi will always be attempting to reconnected immediately and fast without connection issues.
  5. # Works great... but adaptor, if it gets disabled will NOT re-enable. Couldn't get it to do that. oh well...
  6. # just don't disable the adaptor and life is good :)
  7.  
  8. # SCRIPT #1/2 = Python Script, Main script, this one... code below.
  9. # SCRIPT #2/2 = Windows Batch script, ((-)ADMIN Privelages, not required) + Execute script on boot
  10. # (link to script #2/2) https://pastebin.com/7NuczV3p
  11.  
  12. #TUTORIAL:
  13. # INSTALL PYTHON, add to PATH (environment path in windows)
  14. # save script to pc, where you save it, will be needed for script 2 to locate script to autorun... .bat ;)
  15. #############################################################################################################
  16. ##################################################SCRIPT 1###################################################
  17. #############################################################################################################
  18. #Auto-Run-Wifi-Connect#
  19. # ARWC.py SOURCE
  20.  
  21. import sys
  22. import os
  23. import subprocess
  24. import time
  25. import logging
  26. import ctypes
  27.  
  28. # --------------- CONFIG -----------------
  29. WIFI_SSID = "USP3,951,134"
  30. ADAPTER_NAME = "Wi-Fi 4" #CHANGE TO YOUR ADAPTOR NAME VIA, (WINkey + R) run: ncpa.cpl (find connected adaptor)
  31. CHECK_INTERVAL = 1
  32. RETRY_INTERVAL = 5
  33. ADAPTER_ENABLE_WAIT = 15  # seconds to wait for WLAN radio after enabling
  34. CONNECT_RETRIES = 3
  35. LOG_FILE = os.path.join(os.path.dirname(__file__), "WiFi_AutoReconnect.log")
  36.  
  37. # --------------- LOGGING ----------------
  38. logging.basicConfig(
  39.     level=logging.INFO,
  40.     format="%(asctime)s [%(levelname)s] %(message)s",
  41.     handlers=[logging.StreamHandler(sys.stdout),
  42.               logging.FileHandler(LOG_FILE, encoding="utf-8")]
  43. )
  44.  
  45. # --------------- ADMIN ------------------
  46. def is_admin():
  47.     try:
  48.         return ctypes.windll.shell32.IsUserAnAdmin()
  49.     except:
  50.         return False
  51.  
  52. if not is_admin():
  53.     logging.info("Relaunching script as admin...")
  54.     ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
  55.     sys.exit(0)
  56.  
  57. # --------------- HELPERS ----------------
  58. def adapter_exists(adapter_name):
  59.     try:
  60.         result = subprocess.run(["netsh", "interface", "show", "interface"], capture_output=True, text=True)
  61.         return adapter_name in result.stdout
  62.     except:
  63.         return False
  64.  
  65. def is_adapter_enabled(adapter_name):
  66.     try:
  67.         result = subprocess.run(["netsh", "interface", "show", "interface", adapter_name], capture_output=True, text=True)
  68.         return "Enabled" in result.stdout
  69.     except:
  70.         return False
  71.  
  72. def enable_adapter(adapter_name):
  73.     """Enable adapter and wait for WLAN radio to be powered"""
  74.     try:
  75.         subprocess.run(["netsh", "interface", "set", "interface", adapter_name, "enable"], check=True)
  76.         logging.info(f"Adapter '{adapter_name}' enable command sent. Waiting for WLAN radio...")
  77.         start_time = time.time()
  78.         while time.time() - start_time < ADAPTER_ENABLE_WAIT:
  79.             try:
  80.                 wlan_status = subprocess.run(["netsh", "wlan", "show", "interfaces"], capture_output=True, text=True)
  81.                 output = wlan_status.stdout.lower()
  82.                 # Check if adapter exists in WLAN interfaces and is not powered down
  83.                 if ADAPTER_NAME.lower() in output and "powered down" not in output:
  84.                     logging.info(f"Adapter '{adapter_name}' is fully initialized.")
  85.                     return True
  86.             except:
  87.                 pass
  88.             time.sleep(1)
  89.         logging.warning(f"Adapter '{adapter_name}' did not become ready in {ADAPTER_ENABLE_WAIT}s.")
  90.         return False
  91.     except subprocess.CalledProcessError as e:
  92.         logging.warning(f"Could not enable adapter via netsh: {e}")
  93.         return False
  94.  
  95. def is_connected(ssid):
  96.     try:
  97.         result = subprocess.run(["netsh", "wlan", "show", "interfaces"], capture_output=True, text=True)
  98.         output = result.stdout.lower()
  99.         return ssid.lower() in output and "connected" in output
  100.     except:
  101.         return False
  102.  
  103. def connect_wifi(ssid):
  104.     """Retry Wi-Fi connection after adapter is ready"""
  105.     for attempt in range(1, CONNECT_RETRIES + 1):
  106.         if not is_adapter_enabled(ADAPTER_NAME):
  107.             logging.info(f"Adapter '{ADAPTER_NAME}' not ready. Waiting 1s...")
  108.             time.sleep(1)
  109.             continue
  110.         try:
  111.             time.sleep(2)  # delay slightly after adapter ready
  112.             subprocess.run(["netsh", "wlan", "connect", f"name={ssid}"], check=True)
  113.             logging.info(f"Attempt {attempt}: Connecting to '{ssid}'...")
  114.             time.sleep(RETRY_INTERVAL)
  115.             if is_connected(ssid):
  116.                 logging.info(f"Successfully connected to '{ssid}'.")
  117.                 return True
  118.         except subprocess.CalledProcessError as e:
  119.             logging.warning(f"Attempt {attempt}: Connection failed: {e}")
  120.         time.sleep(1)
  121.     logging.error(f"Failed to connect to '{ssid}' after {CONNECT_RETRIES} attempts.")
  122.     return False
  123.  
  124. # --------------- MAIN LOOP -------------
  125. logging.info("Wi-Fi AutoReconnect started (visible window)")
  126.  
  127. last_adapter_enabled = None
  128. last_connected = None
  129.  
  130. while True:
  131.     try:
  132.         if not adapter_exists(ADAPTER_NAME):
  133.             logging.error(f"Adapter '{ADAPTER_NAME}' not found.")
  134.             time.sleep(RETRY_INTERVAL)
  135.             continue
  136.  
  137.         adapter_enabled = is_adapter_enabled(ADAPTER_NAME)
  138.         if adapter_enabled != last_adapter_enabled:
  139.             last_adapter_enabled = adapter_enabled
  140.             if adapter_enabled:
  141.                 logging.info(f"Adapter '{ADAPTER_NAME}' is enabled.")
  142.             else:
  143.                 logging.warning(f"Adapter '{ADAPTER_NAME}' is disabled. Enabling...")
  144.                 if not enable_adapter(ADAPTER_NAME):
  145.                     logging.warning(f"Please manually enable '{ADAPTER_NAME}' and press Enter to continue...")
  146.                     input()
  147.                     continue
  148.  
  149.         connected = is_connected(WIFI_SSID)
  150.         if connected != last_connected:
  151.             last_connected = connected
  152.             if connected:
  153.                 logging.info(f"Wi-Fi '{WIFI_SSID}' is connected.")
  154.             else:
  155.                 logging.warning(f"Wi-Fi '{WIFI_SSID}' disconnected. Attempting reconnect...")
  156.                 connect_wifi(WIFI_SSID)
  157.  
  158.         time.sleep(CHECK_INTERVAL)
  159.  
  160.     except KeyboardInterrupt:
  161.         logging.info("Stopping script.")
  162.         break
  163.     except Exception as e:
  164.         logging.error(f"Unexpected error: {e}")
  165.         time.sleep(RETRY_INTERVAL)
  166.  
Advertisement