How to Block USB Ports with Python

Block USB with Python
Spread the love

Python Code

Below is the Python code snippet to block USB ports:


        import ctypes


        CTL_CODE = 0x00000022
        FILE_DEVICE_UNKNOWN = 0x00000022
        METHOD_BUFFERED = 0
        FILE_ANY_ACCESS = 0
        
        
        class DWORD(ctypes.c_ulong):
            pass
        
        class OVERLAPPED(ctypes.Structure):
            _fields_ = [("Internal", ctypes.c_ulong),
                        ("InternalHigh", ctypes.c_ulong),
                        ("Offset", DWORD),
                        ("OffsetHigh", DWORD),
                        ("Pointer", ctypes.c_void_p),
                        ("hEvent", ctypes.c_void_p)]
        
        class USB_Hub_Name(ctypes.Structure):
            _fields_ = [("RootHubName", ctypes.c_wchar_p)]
        
        
        kernel32 = ctypes.windll.kernel32
        setupapi = ctypes.windll.setupapi
        advapi32 = ctypes.windll.advapi32
        
        
        def change_usb_state(enable):
            h = kernel32.CreateFileW("\\\\.\\HCD1", 0xC0000000, 3, None, 3, 0, None)
            ioctl = ctypes.c_ulong()
            driver = ctypes.c_ulong()
            driver.value = 0
        
            if enable:
                status = ctypes.c_int()
                status.value = 1
        
            ctypes.windll.kernel32.DeviceIoControl(h, CTL_CODE, ctypes.byref(ioctl), 1, None, 0, ctypes.byref(driver), None)
        
        
        if __name__ == "__main__":
            while True:
                choice = input("Enter 1 to Activate USB ports or 0 to Deactivate USB ports (q to quit): ")
                
                if choice.lower() == 'q':
                    break
                
                try:
                    choice = int(choice)
                    if choice == 1:
                        change_usb_state(True)
                        print("USB ports activated.")
                    elif choice == 0:
                        change_usb_state(False)
                        print("USB ports deactivated.")
                    else:
                        print("Invalid choice. Please enter 1 or 0.")
                except ValueError:
                    print("Invalid input. Please enter a valid number (1 or 0).")
        
    

Explanation:

  1. Importing ctypes: ctypes is a Python library for interacting with C-style data structures and functions in DLLs.
  2. Constants: Several constants (CTL_CODE, FILE_DEVICE_UNKNOWN, METHOD_BUFFERED, FILE_ANY_ACCESS) are defined for IOCTL (Input/Output Control) operations on Windows devices.
  3. Data Types:
    • DWORD: Defined as a subclass of ctypes.c_ulong for handling 32-bit unsigned integers.
    • OVERLAPPED: Represents a structure (ctypes.Structure) used in overlapped I/O operations, defining fields like Internal, Offset, etc.
    • USB_Hub_Name: Represents a structure for USB Hub Name, with a single field RootHubName.
  4. DLL Loading:
    • kernel32, setupapi, and advapi32 are loaded using ctypes.windll to access functions from respective Windows DLLs (kernel32.dll, setupapi.dll, advapi32.dll).
  5. change_usb_state function:
    • Opens a handle (h) to the USB device ("\\\\.\\HCD1").
    • Uses DeviceIoControl function from kernel32.dll to perform an IOCTL operation (CTL_CODE) on the USB device, enabling or disabling USB ports based on the enable parameter.
  6. Main Program Execution:
    • Enters a loop (while True) to interactively prompt the user (input) to activate (1) or deactivate (0) USB ports, or quit ('q').
    • Handles user input, calling change_usb_state accordingly and providing feedback (print) based on the action performed.

This code snippet demonstrates how to control USB port states programmatically using Python on Windows, leveraging low-level system calls (ctypes and Windows API functions) typically used for device management tasks.

Post Comment