40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
import pyudev
|
|
import signal
|
|
import sys
|
|
|
|
def on_usb_attached(device):
|
|
print(f"USB device attached: {device.device_node or device.sys_name}")
|
|
|
|
def on_usb_detached(device):
|
|
print(f"USB device detached: {device.device_node or device.sys_name}")
|
|
|
|
def list_current_usb_devices():
|
|
print("Currently attached USB devices:")
|
|
context = pyudev.Context()
|
|
for device in context.list_devices(subsystem='usb', DEVTYPE='usb_device'):
|
|
print(f"- {device.device_node or device.sys_name} ({device.get('ID_MODEL', 'Unknown Device')})")
|
|
print()
|
|
|
|
def monitor_usb():
|
|
context = pyudev.Context()
|
|
monitor = pyudev.Monitor.from_netlink(context)
|
|
monitor.filter_by(subsystem='usb') # Only USB devices
|
|
|
|
for device in iter(monitor.poll, None):
|
|
if device.action == 'add':
|
|
on_usb_attached(device)
|
|
elif device.action == 'remove':
|
|
on_usb_detached(device)
|
|
|
|
def signal_handler(sig, frame):
|
|
print("\nStopping USB monitor...")
|
|
sys.exit(0)
|
|
|
|
if __name__ == "__main__":
|
|
signal.signal(signal.SIGINT, signal_handler)
|
|
|
|
list_current_usb_devices()
|
|
print("Monitoring USB devices. Press Ctrl+C to exit.\n")
|
|
|
|
monitor_usb()
|