50 lines
1.5 KiB
Python
50 lines
1.5 KiB
Python
import pyudev
|
|
import signal
|
|
import logging
|
|
import sys
|
|
import os
|
|
|
|
|
|
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__":
|
|
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
|
|
try:
|
|
CURRENT_NODE_NAME=os.environ['CURRENT_NODE_NAME']
|
|
logging.info(f"Starging USB-watch on {CURRENT_NODE_NAME}")
|
|
except KeyError:
|
|
logging.error('Environment variabel CURRENT_NODE_NAME is not set')
|
|
sys.exit(1)
|
|
signal.signal(signal.SIGINT, signal_handler)
|
|
|
|
list_current_usb_devices()
|
|
logging.info("Monitoring USB device changes......")
|
|
|
|
monitor_usb()
|