#!/usr/bin/python3 import subprocess REALTEK_PRODUCT_ID = "0bda:8153" UHUBCTL_PATH = "/opt/homebrew/bin/uhubctl" def log_message(message): """ Log messages to the system log using logger. """ subprocess.run(['/usr/bin/logger', '-p', 'user.info', '-t', 'networkAdapterReset', f"[networkAdapterReset]: {message}"]) # Print to stderr as well print(message) def find_realtek_device(): """ Finds the hub and port for the Realtek device using uhubctl. """ try: result = subprocess.run([UHUBCTL_PATH], stdout=subprocess.PIPE, text=True) lines = result.stdout.splitlines() current_hub_id = None for i, line in enumerate(lines): # e.g. first line in hub information: "Current status for hub 0-2 ..." if "Current status for hub" in line: current_hub_id = line.split()[4] if REALTEK_PRODUCT_ID in line: # This is the product ID for the Realtek device # E.g. ' Port 4: 0203 power 5gbps U0 enable connect [0bda:8153 Realtek USB 10/100/1000 LAN 001000001]' port_line = line.strip() port_id = port_line.split()[1].split(':')[0] return current_hub_id, port_id except Exception as e: log_message(f"Error finding Realtek device: {str(e)}") return None, None def power_cycle_usb(hub_id, port_id): """ Power cycles the USB port. """ try: # Turning off the power to the port run_args = [UHUBCTL_PATH, '--location', hub_id, '--ports', port_id, '--action', 'cycle', '--delay', '1'] subprocess.run(run_args, check=True) log_message(f"Successfully power cycled hub {hub_id}, port {port_id}.") except subprocess.CalledProcessError as e: log_message(f"Failed to toggle USB: {str(e)}") def main(): log_message("Starting network adapter reset script.") hub_id, port_id = find_realtek_device() if hub_id and port_id: log_message(f"Detected hub: {hub_id}, port: {port_id}") power_cycle_usb(hub_id, port_id) else: log_message("Realtek USB 10/100/1000 LAN device not found.") if __name__ == "__main__": main()