Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #############################################################################################################
- # AUTORUN WIFI CONNECT when disconnected IMMEDIATELY after disconnect, and every 30 seconds thereafter.
- # This project is used (for me personally) for RDP access on a LAN PC RIG. Using this script, i can make sure
- # my wifi will always be attempting to reconnected immediately and fast without connection issues.
- # Works great... but adaptor, if it gets disabled will NOT re-enable. Couldn't get it to do that. oh well...
- # just don't disable the adaptor and life is good :)
- # SCRIPT #1/2 = Python Script, Main script, this one... code below.
- # SCRIPT #2/2 = Windows Batch script, ((-)ADMIN Privelages, not required) + Execute script on boot
- # (link to script #2/2) https://pastebin.com/7NuczV3p
- #TUTORIAL:
- # INSTALL PYTHON, add to PATH (environment path in windows)
- # save script to pc, where you save it, will be needed for script 2 to locate script to autorun... .bat ;)
- #############################################################################################################
- ##################################################SCRIPT 1###################################################
- #############################################################################################################
- #Auto-Run-Wifi-Connect#
- # ARWC.py SOURCE
- import sys
- import os
- import subprocess
- import time
- import logging
- import ctypes
- # --------------- CONFIG -----------------
- WIFI_SSID = "USP3,951,134"
- ADAPTER_NAME = "Wi-Fi 4" #CHANGE TO YOUR ADAPTOR NAME VIA, (WINkey + R) run: ncpa.cpl (find connected adaptor)
- CHECK_INTERVAL = 1
- RETRY_INTERVAL = 5
- ADAPTER_ENABLE_WAIT = 15 # seconds to wait for WLAN radio after enabling
- CONNECT_RETRIES = 3
- LOG_FILE = os.path.join(os.path.dirname(__file__), "WiFi_AutoReconnect.log")
- # --------------- LOGGING ----------------
- logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s [%(levelname)s] %(message)s",
- handlers=[logging.StreamHandler(sys.stdout),
- logging.FileHandler(LOG_FILE, encoding="utf-8")]
- )
- # --------------- ADMIN ------------------
- def is_admin():
- try:
- return ctypes.windll.shell32.IsUserAnAdmin()
- except:
- return False
- if not is_admin():
- logging.info("Relaunching script as admin...")
- ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
- sys.exit(0)
- # --------------- HELPERS ----------------
- def adapter_exists(adapter_name):
- try:
- result = subprocess.run(["netsh", "interface", "show", "interface"], capture_output=True, text=True)
- return adapter_name in result.stdout
- except:
- return False
- def is_adapter_enabled(adapter_name):
- try:
- result = subprocess.run(["netsh", "interface", "show", "interface", adapter_name], capture_output=True, text=True)
- return "Enabled" in result.stdout
- except:
- return False
- def enable_adapter(adapter_name):
- """Enable adapter and wait for WLAN radio to be powered"""
- try:
- subprocess.run(["netsh", "interface", "set", "interface", adapter_name, "enable"], check=True)
- logging.info(f"Adapter '{adapter_name}' enable command sent. Waiting for WLAN radio...")
- start_time = time.time()
- while time.time() - start_time < ADAPTER_ENABLE_WAIT:
- try:
- wlan_status = subprocess.run(["netsh", "wlan", "show", "interfaces"], capture_output=True, text=True)
- output = wlan_status.stdout.lower()
- # Check if adapter exists in WLAN interfaces and is not powered down
- if ADAPTER_NAME.lower() in output and "powered down" not in output:
- logging.info(f"Adapter '{adapter_name}' is fully initialized.")
- return True
- except:
- pass
- time.sleep(1)
- logging.warning(f"Adapter '{adapter_name}' did not become ready in {ADAPTER_ENABLE_WAIT}s.")
- return False
- except subprocess.CalledProcessError as e:
- logging.warning(f"Could not enable adapter via netsh: {e}")
- return False
- def is_connected(ssid):
- try:
- result = subprocess.run(["netsh", "wlan", "show", "interfaces"], capture_output=True, text=True)
- output = result.stdout.lower()
- return ssid.lower() in output and "connected" in output
- except:
- return False
- def connect_wifi(ssid):
- """Retry Wi-Fi connection after adapter is ready"""
- for attempt in range(1, CONNECT_RETRIES + 1):
- if not is_adapter_enabled(ADAPTER_NAME):
- logging.info(f"Adapter '{ADAPTER_NAME}' not ready. Waiting 1s...")
- time.sleep(1)
- continue
- try:
- time.sleep(2) # delay slightly after adapter ready
- subprocess.run(["netsh", "wlan", "connect", f"name={ssid}"], check=True)
- logging.info(f"Attempt {attempt}: Connecting to '{ssid}'...")
- time.sleep(RETRY_INTERVAL)
- if is_connected(ssid):
- logging.info(f"Successfully connected to '{ssid}'.")
- return True
- except subprocess.CalledProcessError as e:
- logging.warning(f"Attempt {attempt}: Connection failed: {e}")
- time.sleep(1)
- logging.error(f"Failed to connect to '{ssid}' after {CONNECT_RETRIES} attempts.")
- return False
- # --------------- MAIN LOOP -------------
- logging.info("Wi-Fi AutoReconnect started (visible window)")
- last_adapter_enabled = None
- last_connected = None
- while True:
- try:
- if not adapter_exists(ADAPTER_NAME):
- logging.error(f"Adapter '{ADAPTER_NAME}' not found.")
- time.sleep(RETRY_INTERVAL)
- continue
- adapter_enabled = is_adapter_enabled(ADAPTER_NAME)
- if adapter_enabled != last_adapter_enabled:
- last_adapter_enabled = adapter_enabled
- if adapter_enabled:
- logging.info(f"Adapter '{ADAPTER_NAME}' is enabled.")
- else:
- logging.warning(f"Adapter '{ADAPTER_NAME}' is disabled. Enabling...")
- if not enable_adapter(ADAPTER_NAME):
- logging.warning(f"Please manually enable '{ADAPTER_NAME}' and press Enter to continue...")
- input()
- continue
- connected = is_connected(WIFI_SSID)
- if connected != last_connected:
- last_connected = connected
- if connected:
- logging.info(f"Wi-Fi '{WIFI_SSID}' is connected.")
- else:
- logging.warning(f"Wi-Fi '{WIFI_SSID}' disconnected. Attempting reconnect...")
- connect_wifi(WIFI_SSID)
- time.sleep(CHECK_INTERVAL)
- except KeyboardInterrupt:
- logging.info("Stopping script.")
- break
- except Exception as e:
- logging.error(f"Unexpected error: {e}")
- time.sleep(RETRY_INTERVAL)
Advertisement