Python执行CMD命令禁用USB端口、网卡失效问题求助
Hey there! Let's figure out why your current code isn't working and get you up and running with disabling those peripherals. Your script has a few key issues with how it's handling command-line arguments, permissions, and even the tools you're using for USB control. Let's break this down step by step.
First: Why Your Current Network Adapter Code Fails
Let's look at your original subprocess call:
subprocess.call(["runas", "/user:Administrator", "cmd.exe /c netsh interface set interface '*'..."])
Here are the core problems:
- Incorrect argument splitting:
subprocessexpects each command/flag to be a separate item in the list. You've bundledcmd.exe /c netsh ...into one string—this won't parse correctly. It should be split into individual elements. - Broken netsh syntax: The
netshcommand to disable an interface needs a valid interface name (not just*) and the explicitadmin=disableflag. Wildcards like*don't work for bulk-disabling interfaces directly. - Runas limitations: Using
runaswill prompt for the Administrator password in a separate window, and it doesn't guarantee full elevated privileges in all contexts. A better approach is to run your Python script itself as Administrator.
Fix 1: Properly Disable Network Adapters
First, let's fix the network adapter code. We'll:
- Add a check to ensure the script runs with Administrator privileges.
- Use correct
netshsyntax to list and disable interfaces.
Here's a revised snippet:
import subprocess import ctypes import sys def is_admin(): # Check if the script is running as Administrator try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False def disable_network_adapters(): # List all network interfaces to get their exact names list_interfaces = subprocess.run( ["netsh", "interface", "show", "interface"], capture_output=True, text=True ) print("Available network interfaces:\n", list_interfaces.stdout) # Example: Disable a specific interface (replace with your interface name) # Or loop through the output to disable all interfaces interface_name = "Wi-Fi" # Update this to match your interface subprocess.run( ["netsh", "interface", "set", "interface", interface_name, "admin=disable"], check=True ) print(f"Successfully disabled interface: {interface_name}") def main(): print("PROGRAM STARTED") if not is_admin(): # Re-launch the script with Administrator privileges ctypes.windll.shell32.ShellExecuteW( None, "runas", sys.executable, " ".join(sys.argv), None, 1 ) sys.exit() # Execute network adapter disable logic disable_network_adapters() if __name__ == "__main__": main()
Fix 2: Disable USB Ports (Netsh Can't Do This!)
Netsh is only for network configuration—you need a different tool to disable USB ports. Here are two reliable options:
Option A: Use DevCon (Windows SDK Tool)
DevCon is a command-line device manager tool. You'll need to download it from the Windows SDK first. Once devcon.exe is in your script's directory or system PATH, use this function:
def disable_usb_ports(): # Disable all USB root hubs (adjust the hardware ID to target specific devices if needed) subprocess.run( ["devcon.exe", "disable", "USB\\ROOT_HUB*"], check=True ) print("Disabled USB root hubs")
Add this function to your main() after disabling network adapters.
Option B: Modify the Windows Registry
If you don't want to use DevCon, you can edit the registry to disable USB mass storage. Note: Registry edits can break your system if done incorrectly—test this first in a safe environment.
import winreg def disable_usb_mass_storage(): reg_path = r"SYSTEM\CurrentControlSet\Services\USBSTOR" with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path, 0, winreg.KEY_WRITE) as key: # Set Start value to 4 (disabled; default is 3 for enabled) winreg.SetValueEx(key, "Start", 0, winreg.REG_DWORD, 4) print("Disabled USB mass storage via registry")
To re-enable USB storage, set the Start value back to 3.
Final Notes
- Always test these commands in a non-production environment first—disabling all network interfaces will cut your internet connection, and USB changes can affect all connected USB devices.
- If you need to re-enable peripherals, reverse the commands (replace
admin=disablewithadmin=enablefor netsh, or usedevcon enable/registry value 3 for USB).
内容的提问来源于stack exchange,提问作者bradley plater

