Python pyudev.Context() Examples

The following are 30 code examples of pyudev.Context(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyudev , or try the search function .
Example #1
Source File: disk.py    From ZFSmond with GNU General Public License v3.0 7 votes vote down vote up
def disk_list():
	disks = []

	context = pyudev.Context()
	for device in context.list_devices(subsystem="block"):
		if device.device_type == u"disk":
			property_dict = dict(device.items())

			if ('ID_MODEL' in property_dict):
				disk_short_name = property_dict.get('DEVNAME', "Unknown").split('/')[-1]
				disks.append(
				{
					'model':	property_dict.get('ID_MODEL', "Unknown"),
					'name':		disk_short_name,
					'size':		get_block_device_size(property_dict.get('DEVNAME', None)),
					'serial':	property_dict.get('ID_SERIAL_SHORT', "Unknown"),
				})

	return disks 
Example #2
Source File: main.py    From rshell with MIT License 7 votes vote down vote up
def autoconnect():
    """Sets up a thread to detect when USB devices are plugged and unplugged.
       If the device looks like a MicroPython board, then it will automatically
       connect to it.
    """
    if not USE_AUTOCONNECT:
        return
    try:
        import pyudev
    except ImportError:
        return
    context = pyudev.Context()
    monitor = pyudev.Monitor.from_netlink(context)
    connect_thread = threading.Thread(target=autoconnect_thread, args=(monitor,), name='AutoConnect')
    connect_thread.daemon = True
    connect_thread.start() 
Example #3
Source File: joystick.py    From derplearning with MIT License 6 votes vote down vote up
def __find_device(self):
        context = Context()
        for hidraw_device in context.list_devices(subsystem="hidraw"):
            hid_device = hidraw_device.parent
            if hid_device.subsystem != "hid" or hid_device.get("HID_NAME") != "Wireless Controller":
                continue
            for child in hid_device.parent.children:
                event_device = child.get("DEVNAME", "")
                if event_device.startswith("/dev/input/event"):
                    break
            else:
                continue

            device_addr = hid_device.get("HID_UNIQ", "").upper()
            return device_addr, hidraw_device.device_node, event_device
        return None, None, None 
Example #4
Source File: filesystem.py    From probert with GNU Affero General Public License v3.0 6 votes vote down vote up
def probe(context=None):
    """ Capture detected filesystems found on discovered block devices.  """
    filesystems = {}
    if not context:
        context = pyudev.Context()

    for device in sane_block_devices(context):
        # Ignore block major=1 (ramdisk) and major=7 (loopback)
        # these won't ever be used in recreating storage on target systems.
        if device['MAJOR'] not in ["1", "7"]:
            fs_info = get_device_filesystem(device)
            # The ID_FS_ udev values come from libblkid, which contains code to
            # recognize lots of different things that block devices or their
            # partitions can contain (filesystems, lvm PVs, bcache, ...).  We
            # only want to report things that are mountable filesystems here,
            # which libblkid conveniently tags with ID_FS_USAGE=filesystem.
            # Swap is a bit of a special case because it is not a mountable
            # filesystem in the usual sense, but subiquity still needs to
            # generate mount actions for it.
            if fs_info.get("USAGE") == "filesystem" or \
               fs_info.get("TYPE") == "swap":
                filesystems[device['DEVNAME']] = fs_info

    return filesystems 
Example #5
Source File: udev_integration.py    From fermentrack with MIT License 6 votes vote down vote up
def get_node_from_serial(device_serial):
    try:
        context = pyudev.Context()

        for device in context.list_devices(subsystem="tty"):
            if device.get("ID_SERIAL", "") == device_serial:
                return device.device_node
    except:
        # We weren't able to use pyudev (possibly because of an invalid operating system)
        pass
    return None


# The following was used for testing during development 
Example #6
Source File: storage.py    From probert with GNU Affero General Public License v3.0 6 votes vote down vote up
def blockdev_probe(context=None):
    """ Non-class method for extracting relevant block
        devices from pyudev.Context().
    """
    def _extract_partition_table(devname):
        cmd = ['sfdisk', '--bytes', '--json', devname]
        try:
            result = subprocess.run(cmd, stdout=subprocess.PIPE,
                                    stderr=subprocess.DEVNULL)
            output = result.stdout.decode('utf-8')
        except subprocess.CalledProcessError as e:
            log.error('Failed to probe partition table on %s:%s', devname, e)
            return None
        if not output:
            return None
        ptable = {}
        try:
            ptable = json.loads(output)
        except json.decoder.JSONDecodeError as e:
            log.error('Failed to load sfdisk json output:', e)
        return ptable

    if not context:
        context = pyudev.Context()

    blockdev = {}
    for device in sane_block_devices(context):
        if device['MAJOR'] not in ["1", "7"]:
            attrs = udev_get_attributes(device)
            # update the size attr as it may only be the number
            # of blocks rather than size in bytes.
            attrs['size'] = \
                str(read_sys_block_size_bytes(device['DEVNAME']))
            blockdev[device['DEVNAME']] = dict(device)
            blockdev[device['DEVNAME']].update({'attrs': attrs})
            # include partition table info if present
            ptable = _extract_partition_table(device['DEVNAME'])
            if ptable:
                blockdev[device['DEVNAME']].update(ptable)

    return blockdev 
Example #7
Source File: device_manager.py    From uchroma with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, *callbacks):
        self._logger = Log.get('uchroma.devicemanager')

        self._devices = OrderedDict()
        self._monitor = False
        self._udev_context = Context()
        self._udev_observer = None
        self._callbacks = []

        if callbacks is not None:
            self._callbacks.extend(callbacks)

        self._loop = asyncio.get_event_loop()

        self.device_added = Signal()
        self.device_removed = Signal()

        self.discover() 
Example #8
Source File: donglelock.py    From fittools with MIT License 6 votes vote down vote up
def select_devices():
    context = Context()
    devices = context.list_devices(subsystem="usb") 
    num = 1
    for dev in devices:
        print "%02d- %s %s SerialNo: %s %s" % (num, dev.attributes.get('idVendor'), dev.attributes.get('idProduct'), dev.attributes.get('serial'), dev.attributes.get('manufacturer'))
        num += 1
    try:
        choice = int(raw_input("Select device: [1-%d] " % (num)))
    except ValueError:
        print "Please enter a number!"
        quit()

    assert choice >=1 and choice <= num, "Please enter a valid number"

    num = 1
    for dev in devices:
        if num == choice:
            global verbose
            if verbose: 
                print "Selected device: "
                display_device_attributes(dev)
            global monitored_idVendor
            monitored_idVendor = dev.attributes.get('idVendor')
            global monitored_idProduct 
            monitored_idProduct = dev.attributes.get('idProduct')
            global monitored_serial
            monitored_serial = dev.attributes.get('serial')
            global monitored_path
            monitored_path = dev.device_path
            break
        num +=1 
Example #9
Source File: find_port.py    From usb-ser-mon with MIT License 5 votes vote down vote up
def list_devices(vid=None, pid=None, vendor=None, serial=None, *args,
                 **kwargs):
    devs = []
    context = pyudev.Context()
    for device in context.list_devices(subsystem='tty'):
        if is_usb_serial(device, vid=vid, pid=pid, vendor=vendor,
                         serial=serial):
            devs.append([device.properties['ID_VENDOR_ID'], device.properties['ID_MODEL_ID'],
                         extra_info(device), device.device_node])
    return devs 
Example #10
Source File: usb_drive_mounter.py    From pi_video_looper with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, root='/mnt/usbdrive', readonly=True):
        """Create an instance of the USB drive mounter service.  Root is an
        optional parameter which specifies the location and file name prefix for
        mounted drives (a number will be appended to each mounted drive file
        name).  Readonly is a boolean that indicates if the drives should be
        mounted as read-only or not (default false, writable).
        """
        self._root = root
        self._readonly = readonly
        self._context = pyudev.Context() 
Example #11
Source File: raid.py    From probert with GNU Affero General Public License v3.0 5 votes vote down vote up
def probe(context=None, report=False):
    """Initiate an mdadm assemble to awaken existing MDADM devices.
       For each md block device, extract required information needed
       to describe the array for recreation or reuse as needed.

       mdadm tooling provides information about the raid type,
       the members, the size, the name, uuids, metadata version.
    """
    mdadm_assemble()

    # ignore passed context, must read udev after assembling mdadm devices
    context = pyudev.Context()

    raids = {}
    for device in sane_block_devices(context):
        if 'MD_NAME' in device and device.get('DEVTYPE') == 'disk':
            devname = device['DEVNAME']
            attrs = udev_get_attributes(device)
            attrs['size'] = str(read_sys_block_size_bytes(devname))
            devices, spares = get_mdadm_array_members(devname, device)
            cfg = dict(device)
            cfg.update({'raidlevel': device['MD_LEVEL'],
                        'devices': devices,
                        'spare_devices': spares})
            raids[devname] = cfg

    return raids 
Example #12
Source File: network.py    From probert with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, receiver=None):
        self._links = {}
        self.context = pyudev.Context()
        if receiver is None:
            receiver = TrivialEventReceiver()
        assert isinstance(receiver, NetworkEventReceiver)
        self.receiver = receiver
        self._calls = None 
Example #13
Source File: storage.py    From probert with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, results={}):
        self.results = results
        self.context = pyudev.Context() 
Example #14
Source File: dasd.py    From probert with GNU Affero General Public License v3.0 5 votes vote down vote up
def probe(context=None):
    """Examine all dasd devices present and extract configuration attributes

       This data is useful for determining if the dasd device has been
       formatted, if so what the block size, the partition layout used
       and the s390x device_id used to uniquely identify the device.
    """
    log.debug('Probing DASD devies')
    machine = platform.machine()
    if machine != "s390x":
        log.debug('DASD devices only present on s390x, arch=%s', machine)
        return {}

    dasds = {}
    if not context:
        context = pyudev.Context()

    for device in context.list_devices(subsystem='block'):
        # dasd devices have MAJOR 94
        if device['MAJOR'] != "94":
            continue
        # ignore dasd partitions
        if 'PARTN' in device:
            continue

        try:
            dasd_info = get_dasd_info(device)
        except ValueError as e:
            log.error('Error probing dasd device %s: %s', device['DEVNAME'], e)
            dasd_info = None

        if dasd_info:
            dasds[device['DEVNAME']] = dasd_info

    return dasds 
Example #15
Source File: daemon.py    From openrazer with GNU General Public License v2.0 5 votes vote down vote up
def _init_udev_monitor(self):
        self._udev_context = Context()
        udev_monitor = Monitor.from_netlink(self._udev_context)
        udev_monitor.filter_by(subsystem='hid')
        self._udev_observer = MonitorObserver(udev_monitor, callback=self._udev_input_event, name='device-monitor') 
Example #16
Source File: usb.py    From openag-device-software with GNU General Public License v3.0 5 votes vote down vote up
def device_matches(
    device_path: str, vendor_id: int, product_id: int, friendly: bool = True
) -> bool:
    """Checks if a usb device at specified path matches vendor id and product id."""
    logger.debug("Checking if device matches")

    # Convert device path to real path if friendly
    # TODO: Explain friendly path...
    if friendly:
        command = "udevadm info --name={} -q path".format(device_path)
        process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
        output, error = process.communicate()
        device_path = str(output.strip(), encoding="utf-8")

    # Get device info
    context = pyudev.Context()
    device = pyudev.Device.from_path(context, device_path)
    device_vendor_id = int("0x" + device.get("ID_VENDOR_ID"), 16)
    device_product_id = int("0x" + device.get("ID_MODEL_ID"), 16)

    # Check if ids match
    if vendor_id != device_vendor_id or product_id != device_product_id:
        logger.debug("Device does not match")
        return False

    # USB device matches
    logger.debug("Device matches")
    return True 
Example #17
Source File: find_disks.py    From kolla with Apache License 2.0 5 votes vote down vote up
def main():
    argument_spec = dict(
        match_mode=dict(required=False, choices=['strict', 'prefix'],
                        default='strict'),
        name=dict(aliases=['partition_name'], required=True, type='str'),
        use_udev=dict(required=False, default=True, type='bool')
    )
    module = AnsibleModule(argument_spec)
    match_mode = module.params.get('match_mode')
    name = module.params.get('name')
    use_udev = module.params.get('use_udev')

    try:
        ret = list()
        ct = pyudev.Context()
        for dev in find_disk(ct, name, match_mode, use_udev):
            if '_BS' in name:
                info = extract_disk_info_bs(ct, dev, name, use_udev)
                if info:
                    ret.append(info)
            else:
                for info in extract_disk_info(ct, dev, name, use_udev):
                    if info:
                        ret.append(info)

        if '_BS' in name and len(ret) > 0:
            ret = combine_info(ret)

        module.exit_json(disks=json.dumps(ret))
    except Exception as e:
        module.exit_json(failed=True, msg=repr(e)) 
Example #18
Source File: mouse_client.py    From keyboard_mouse_emulate_on_raspberry with MIT License 5 votes vote down vote up
def init():
        context = pyudev.Context()
        devs = context.list_devices(subsystem="input")
        InputDevice.monitor = pyudev.Monitor.from_netlink(context)
        InputDevice.monitor.filter_by(subsystem='input')
        InputDevice.monitor.start()
        for d in [*devs]:
            InputDevice.add_device(d) 
Example #19
Source File: evdevremapkeys.py    From evdevremapkeys with MIT License 5 votes vote down vote up
def run_loop(args):
    context = pyudev.Context()
    monitor = pyudev.Monitor.from_netlink(context)
    monitor.filter_by('input')
    fd = monitor.fileno()
    monitor.start()

    config = load_config(args.config_file)
    tasks = []
    for device in config['devices']:
        task = register_device(device)
        if task:
            tasks.append(task)

    if not tasks:
        print('No configured devices detected at startup.', flush=True)

    loop = asyncio.get_event_loop()
    loop.add_signal_handler(signal.SIGTERM,
                            functools.partial(asyncio.ensure_future,
                                              shutdown(loop)))
    loop.add_reader(fd, handle_udev_event, monitor, config)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.remove_signal_handler(signal.SIGTERM)
        loop.run_until_complete(asyncio.ensure_future(shutdown(loop)))
    finally:
        loop.close() 
Example #20
Source File: donglelock.py    From fittools with MIT License 5 votes vote down vote up
def monitor():
    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='usb')  
    observer = MonitorObserver(monitor)
    observer.connect('device-removed', remove_event)
    observer.connect('device-added', add_event)
    monitor.start()
    glib.MainLoop().run() 
Example #21
Source File: ioutil.py    From poclbm with GNU General Public License v3.0 5 votes vote down vote up
def find_udev(check, product_id):
	ports = []
	if LINUX:
		try:
			import pyudev

			context = pyudev.Context()
			for device in context.list_devices(subsystem='tty', ID_MODEL=product_id):
				if check(device.device_node):
					ports.append(device.device_node)
		except ImportError:
			pass		
	return ports 
Example #22
Source File: usb_detect_linux.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, usb_plugged, usb_unplugged):
		self.usb_plugged = usb_plugged
		self.usb_unplugged = usb_unplugged
		
		self.context = pyudev.Context()
		self.monitor = pyudev.Monitor.from_netlink(self.context)
		self.monitor.filter_by('block') 
Example #23
Source File: udev_integration.py    From fermentrack with MIT License 5 votes vote down vote up
def get_serial_from_node(device_node):
    try:
        context = pyudev.Context()

        for device in context.list_devices(subsystem="tty"):
            if device.device_node == device_node:
                return device.get("ID_SERIAL")
    except:
        # We weren't able to use pyudev (possibly because of an invalid operating system)
        pass
    return None


# get_node_from_serial() takes a udev serial number, and retuns the associated node (if found) 
Example #24
Source File: wheels.py    From oversteer with GNU General Public License v3.0 5 votes vote down vote up
def wait_for_device(self, device_id):
        context = pyudev.Context()
        monitor = pyudev.Monitor.from_netlink(context)
        monitor.filter_by('input')
        for device in iter(functools.partial(monitor.poll, 2), None):
            if device.action == 'add' and device.get('ID_FOR_SEAT') == device_id:
                self.add_udev_data(device) 
Example #25
Source File: wheels.py    From oversteer with GNU General Public License v3.0 5 votes vote down vote up
def reset(self):
        self.devices = {}

        context = pyudev.Context()
        for device in context.list_devices(subsystem='input', ID_INPUT_JOYSTICK=1):
            if device.get('ID_VENDOR_ID') == '046d' and device.get('ID_MODEL_ID') in self.supported_models:
                self.add_udev_data(device)

        logging.debug('Devices:' + str(self.devices)) 
Example #26
Source File: sriov_config.py    From os-net-config with Apache License 2.0 5 votes vote down vote up
def udev_monitor_setup():
    # Create a context for pyudev and observe udev events for network
    context = pyudev.Context()
    monitor = pyudev.Monitor.from_netlink(context)
    monitor.filter_by('net')
    observer = pyudev.MonitorObserver(monitor, udev_event_handler)
    return observer 
Example #27
Source File: collectd_iostat_python.py    From browbeat with Apache License 2.0 4 votes vote down vote up
def read_callback(self):
        """
        Collectd read callback
        """
        self.log_verbose('Read callback called')
        iostat = IOStat(
            path=self.iostat_path,
            interval=self.iostat_interval,
            count=self.iostat_count,
            disks=self.iostat_disks,
            no_dm_name=self.iostat_no_dm_name)
        ds = iostat.get_diskstats()

        if not ds:
            self.log_verbose('%s plugin: No info received.' % self.plugin_name)
            return

        if self.iostat_udevnameattr and pyudev_available:
            context = pyudev.Context()

        for disk in ds:
            if not re.match(self.iostat_disks_regex, disk):
                continue
            if self.iostat_udevnameattr and pyudev_available:
                device = pyudev.Device.from_device_file(context, "/dev/" + disk)
                if self.skip_multipath:
                    mp_managed = device.get('DM_MULTIPATH_DEVICE_PATH')
                    if mp_managed and mp_managed == '1':
                        self.log_verbose('Skipping physical multipath disk %s' % disk)
                        continue
                if self.iostat_udevnameattr:
                    persistent_name = device.get(self.iostat_udevnameattr)
                    if not persistent_name:
                        self.log_verbose('Unable to determine disk name based on UdevNameAttr: %s' % self.iostat_udevnameattr)
                        persistent_name = disk
            else:
                persistent_name = disk

            for name in ds[disk]:
                if self.iostat_nice_names and name in self.names:
                    val_type = self.names[name]['t']

                    if 'ti' in self.names[name]:
                        type_instance = self.names[name]['ti']
                    else:
                        type_instance = ''

                    value = ds[disk][name]
                    if 'm' in self.names[name]:
                        value *= self.names[name]['m']
                else:
                    val_type = 'gauge'
                    tbl = string.maketrans('/-%', '___')
                    type_instance = name.translate(tbl)
                    value = ds[disk][name]
                self.dispatch_value(
                    persistent_name, val_type, type_instance, value) 
Example #28
Source File: collectd_iostat_python.py    From browbeat with Apache License 2.0 4 votes vote down vote up
def read_callback(self):
        """
        Collectd read callback
        """
        self.log_verbose('Read callback called')
        iostat = IOStat(
            path=self.iostat_path,
            interval=self.iostat_interval,
            count=self.iostat_count,
            disks=self.iostat_disks,
            no_dm_name=self.iostat_no_dm_name)
        ds = iostat.get_diskstats()

        if not ds:
            self.log_verbose('%s plugin: No info received.' % self.plugin_name)
            return

        if self.iostat_udevnameattr and pyudev_available:
            context = pyudev.Context()

        for disk in ds:
            if not re.match(self.iostat_disks_regex, disk):
                continue
            if self.iostat_udevnameattr and pyudev_available:
                device = pyudev.Device.from_device_file(context, "/dev/" + disk)
                if self.skip_multipath:
                    mp_managed = device.get('DM_MULTIPATH_DEVICE_PATH')
                    if mp_managed and mp_managed == '1':
                        self.log_verbose('Skipping physical multipath disk %s' % disk)
                        continue
                if self.iostat_udevnameattr:
                    persistent_name = device.get(self.iostat_udevnameattr)
                    if not persistent_name:
                        self.log_verbose('Unable to determine disk name based on UdevNameAttr: %s' % self.iostat_udevnameattr)
                        persistent_name = disk
            else:
                persistent_name = disk

            for name in ds[disk]:
                if self.iostat_nice_names and name in self.names:
                    val_type = self.names[name]['t']

                    if 'ti' in self.names[name]:
                        type_instance = self.names[name]['ti']
                    else:
                        type_instance = ''

                    value = ds[disk][name]
                    if 'm' in self.names[name]:
                        value *= self.names[name]['m']
                else:
                    val_type = 'gauge'
                    tbl = string.maketrans('/-%', '___')
                    type_instance = name.translate(tbl)
                    value = ds[disk][name]
                self.dispatch_value(
                    persistent_name, val_type, type_instance, value) 
Example #29
Source File: collectd_iostat_python.py    From collectd-iostat-python with MIT License 4 votes vote down vote up
def read_callback(self):
        """
        Collectd read callback
        """
        self.log_verbose('Read callback called')
        iostat = IOStat(
            path=self.iostat_path,
            interval=self.iostat_interval,
            count=self.iostat_count,
            disks=self.iostat_disks,
            no_dm_name=self.iostat_no_dm_name)
        ds = iostat.get_diskstats()

        if not ds:
            self.log_verbose('%s plugin: No info received.' % self.plugin_name)
            return

        if self.iostat_udevnameattr and pyudev_available:
            context = pyudev.Context()

        for disk in ds:
            if not re.match(self.iostat_disks_regex, disk):
                continue
            if self.iostat_udevnameattr and pyudev_available:
                device = pyudev.Device.from_device_file(context, "/dev/" + disk)
                if self.skip_multipath:
                    mp_managed = device.get('DM_MULTIPATH_DEVICE_PATH')
                    if mp_managed and mp_managed == '1':
                        self.log_verbose('Skipping physical multipath disk %s' % disk)
                        continue
                if self.iostat_udevnameattr:
                    persistent_name = device.get(self.iostat_udevnameattr)
                    if not persistent_name:
                        self.log_verbose('Unable to determine disk name based on UdevNameAttr: %s' % self.iostat_udevnameattr)
                        persistent_name = disk
            else:
                persistent_name = disk

            for name in ds[disk]:
                if self.iostat_nice_names and name in self.names:
                    val_type = self.names[name]['t']

                    if 'ti' in self.names[name]:
                        type_instance = self.names[name]['ti']
                    else:
                        type_instance = ''

                    value = ds[disk][name]
                    if 'm' in self.names[name]:
                        value *= self.names[name]['m']
                else:
                    val_type = 'gauge'
                    tbl = string.maketrans('/-%', '___')
                    type_instance = name.translate(tbl)
                    value = ds[disk][name]
                self.dispatch_value(
                    persistent_name, val_type, type_instance, value) 
Example #30
Source File: statsd-agent.py    From dino with Apache License 2.0 4 votes vote down vote up
def smart():
    c = statsd.StatsClient(STATSD_HOST, 8125, prefix=PREFIX + 'system.smart')
    context = pyudev.Context()
    devices = list()

    for device in context.list_devices(MAJOR='8'):
        if device.device_type == 'disk':
            devices.append(device.device_node)

    while True:
        for device in devices:
            try:
                process = subprocess.Popen([
                    'sudo', 'smartctl', '--attributes',
                    '-d', 'sat+megaraid,0', device
                ], stdout=subprocess.PIPE)

                out, _ = process.communicate()
                out = str(out, 'utf-8').strip()
                out = out.split('\n')
                out = out[7:-2]

                for line in out:
                    try:
                        line = line.split()[0:10]
                        key = '{}.{}_{}'.format(device.split('/')[-1], line[1], line[0])
                        value = int(float(line[-1]))
                        c.gauge(key, value)
                    except Exception as inner_e:
                        print('could not parse line: {}\n{}'.format(str(inner_e), line))
            except Exception as e:
                print('error: %s' % str(e))
        time.sleep(GRANULARITY * 6)