Skip to content

Other options than shutdown #4

@Lvl4Sword

Description

@Lvl4Sword

What are some other options? Here's unbinding the added device ( USB-only for now ).
Just an example, not for production:

import asyncio
import pyudev

usb_devices = {}
usb_ids = {}


def get_all_usb():
    all_usb_devices = context.list_devices(subsystem='usb')
    for each_device in all_usb_devices:
        if each_device.device_node is not None:
            this_device = each_device.get('DEVPATH')
            device_ids = f"{each_device.get('ID_VENDOR_ID')}{each_device.get('ID_MODEL_ID')}"
            if device_ids in usb_ids:
                usb_ids[device_ids] += 1
            else:
                usb_ids[device_ids] = 1
            if this_device in usb_devices:
                usb_devices[this_device]['amount'] += 1
            else:
                usb_devices[this_device] = {}
                usb_devices[this_device]['amount'] = 1
                usb_devices[this_device]['ids'] = device_ids


async def main(monitor):
    for device in iter(monitor.poll, None):
        if device.get("SUBSYSTEM") == "usb":
            the_devpath = device.get('DEVPATH')
            the_specific_port = the_devpath.split('/')[-1]
            device_ids = f"{device.get('ID_VENDOR_ID')}:{device.get('ID_MODEL_ID')}"
            if device.get('ID_VENDOR_ID') is not None and device.get('ID_MODEL_ID') is not None:
                if device.action == 'add':
                    usb_devices[the_devpath] = device_ids
                    with open("/sys/bus/usb/drivers/usb/unbind", 'w') as usb_unbind:
                        usb_unbind.write(the_specific_port)
                elif device.action == 'remove':
                    if device.get('DEVPATH') in usb_devices:
                        usb_devices.pop(the_devpath)


if __name__ == '__main__':
    context = pyudev.Context()
    get_all_usb()
    pyudev_monitor = pyudev.Monitor.from_netlink(context)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    asyncio.run(main(pyudev_monitor))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions