You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python执行CMD命令禁用USB端口、网卡失效问题求助

Fixing Your Python Script to Disable Network Adapters & USB Ports

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: subprocess expects each command/flag to be a separate item in the list. You've bundled cmd.exe /c netsh ... into one string—this won't parse correctly. It should be split into individual elements.
  • Broken netsh syntax: The netsh command to disable an interface needs a valid interface name (not just *) and the explicit admin=disable flag. Wildcards like * don't work for bulk-disabling interfaces directly.
  • Runas limitations: Using runas will 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:

  1. Add a check to ensure the script runs with Administrator privileges.
  2. Use correct netsh syntax 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=disable with admin=enable for netsh, or use devcon enable/registry value 3 for USB).

内容的提问来源于stack exchange,提问作者bradley plater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:51:14