Ejemplo n.º 1
0
 def __attrs_post_init__(self):
     super().__attrs_post_init__()
     self.log = logging.getLogger('UdevManager')
     self._context = pyudev.Context()
     self._monitor = pyudev.Monitor.from_netlink(self._context)
     self._monitor.start()
Ejemplo n.º 2
0
def list_devices(fixed=False):
    """
    List inserted USB devices.
    :return: USB devices as list.
    """
    devices = []
    if platform.system() == "Linux":
        try:
            # pyudev is good enough to detect USB devices on modern Linux machines.
            gen.log("Using pyudev for detecting USB drives...")
            try:
                import pyudev
            except Exception as e:
                gen.log(
                    'PyUdev is not installed on host system, using built-in.')
                from . import pyudev
            context = pyudev.Context()

            for device in context.list_devices(subsystem='block',
                                               ID_BUS="usb"):
                devices.append(str(device['DEVNAME']))
                gen.log("\t" + device['DEVNAME'])

            if fixed is True:
                for device in context.list_devices(subsystem='block'):
                    if device.get('DEVTYPE') in [
                            'disk', 'partition'
                    ] and device.get('ID_PART_TABLE_TYPE'):
                        if device['DEVNAME'] not in devices:
                            devices.append(str(device['DEVNAME']))
                            gen.log("\t" + device['DEVNAME'])

        except Exception as e:
            gen.log(e)
            import dbus
            bus = dbus.SystemBus()
            try:
                # You should come here only if your system does'nt have udev installed.
                # We will use udiskd2 for now.
                gen.log("Falling back to Udisks2..")
                ud_manager_obj = bus.get_object('org.freedesktop.UDisks2',
                                                '/org/freedesktop/UDisks2')
                ud_manager = dbus.Interface(
                    ud_manager_obj, 'org.freedesktop.DBus.ObjectManager')
                for k, v in ud_manager.GetManagedObjects().items():
                    drive_info = v.get('org.freedesktop.UDisks2.Block', {})
                    if fixed is True:
                        if drive_info.get(
                                'IdUsage'
                        ) == "filesystem" and not drive_info.get('ReadOnly'):
                            device = drive_info.get('Device')
                            device = bytearray(device).replace(
                                b'\x00', b'').decode('utf-8')
                            devices.append(device)
                    else:
                        if drive_info.get(
                                'IdUsage'
                        ) == "filesystem" and not drive_info.get(
                                'HintSystem') and not drive_info.get(
                                    'ReadOnly'):
                            device = drive_info.get('Device')
                            device = bytearray(device).replace(
                                b'\x00', b'').decode('utf-8')
                            devices.append(device)

            except Exception as e:
                gen.log(e, error=True)
                try:
                    # You must be using really old distro. Otherwise, the code
                    # should not reach here.
                    gen.log("Falling back to Udisks1...")
                    ud_manager_obj = bus.get_object("org.freedesktop.UDisks",
                                                    "/org/freedesktop/UDisks")
                    ud_manager = dbus.Interface(ud_manager_obj,
                                                'org.freedesktop.UDisks')
                    for dev in ud_manager.EnumerateDevices():
                        device_obj = bus.get_object("org.freedesktop.UDisks",
                                                    dev)
                        device_props = dbus.Interface(device_obj,
                                                      dbus.PROPERTIES_IFACE)
                        if device_props.Get(
                                'org.freedesktop.UDisks.Device',
                                "DriveConnectionInterface"
                        ) == "usb" and device_props.Get(
                                'org.freedesktop.UDisks.Device',
                                "DeviceIsPartition"):
                            if device_props.Get(
                                    'org.freedesktop.UDisks.Device',
                                    "DeviceIsMounted"):
                                device_file = device_props.Get(
                                    'org.freedesktop.UDisks.Device',
                                    "DeviceFile")
                                devices.append(device_file)
                except Exception as e:
                    gen.log(e, error=True)
                    gen.log("No USB device found...")

        devices.sort()

    elif platform.system() == "Windows":
        if fixed is True:
            for drive in psutil.disk_partitions():
                if 'cdrom' in drive.opts or drive.fstype == '':
                    # Skip cdrom drives or the disk with no filesystem
                    continue
                devices.append(drive[0][:-1])
        else:
            try:
                # Try new method using psutil. It should also detect USB 3.0 (but not tested by me)
                for drive in psutil.disk_partitions():
                    if 'cdrom' in drive.opts or drive.fstype == '':
                        # Skip cdrom drives or the disk with no filesystem
                        continue
                    if 'removable' in drive.opts:
                        devices.append(drive[0][:-1])
            except:
                # Revert back to old method if psutil fails (which is unlikely)
                oFS = win32com.client.Dispatch("Scripting.FileSystemObject")
                oDrives = oFS.Drives
                for drive in oDrives:
                    if drive.DriveType == 1 and drive.IsReady:
                        devices.append(drive)

    if devices:
        return devices
    else:
        gen.log("No USB device found...")
        return None
Ejemplo n.º 3
0
def _NumatoUsbDetect():
  context = pyudev.Context()
  tty_devices = context.list_devices(subsystem='tty')
  for dev in tty_devices.match_property('ID_VENDOR_ID', '2a19'):
    numato_id = _NumatoRead(dev.device_node, 'id get')
    yield dev.device_node, numato_id
Ejemplo n.º 4
0
 def get_gamepad(cls):
     context = pyudev.Context()
     for js_device in context.list_devices(subsystem="input", ID_INPUT_JOYSTICK=1):
         if js_device.device_node:
             return cls(js_device)
Ejemplo n.º 5
0
def get_udev_devices(job=None, logger=None, device_info=None):
    """
    Get udev device nodes based on serial, vendor and product ID
    All subsystems are allowed so that additional hardware like
    tty devices can be added to the LXC. The ID to match is controlled
    by the lab admin.
    """
    context = pyudev.Context()
    device_paths = set()
    devices = []
    if job:
        devices = job.device.get("device_info", [])
    # device_info argument overrides job device_info
    if device_info:
        devices = device_info
    if not devices:
        return []
    added = set()
    for usb_device in devices:
        board_id = str(usb_device.get("board_id", ""))
        usb_vendor_id = str(usb_device.get("usb_vendor_id", ""))
        usb_product_id = str(usb_device.get("usb_product_id", ""))
        usb_fs_label = str(usb_device.get("fs_label", ""))
        # check if device is already connected
        # try with all parameters such as board id, usb_vendor_id and
        # usb_product_id
        for device in context.list_devices():
            if board_id and usb_vendor_id and usb_product_id:
                if ((device.get("ID_SERIAL_SHORT") == board_id)
                        and (device.get("ID_VENDOR_ID") == usb_vendor_id)
                        and (device.get("ID_MODEL_ID") == usb_product_id)):
                    device_paths.add(device.device_node)
                    added.add(board_id)
                    for child in device.children:
                        if child.device_node:
                            device_paths.add(child.device_node)
                    for link in device.device_links:
                        device_paths.add(link)
            elif board_id and usb_vendor_id and not usb_product_id:
                # try with parameters such as board id, usb_vendor_id
                if (device.get("ID_SERIAL_SHORT")
                        == board_id) and (device.get("ID_VENDOR_ID")
                                          == usb_vendor_id):
                    device_paths.add(device.device_node)
                    added.add(board_id)
                    for child in device.children:
                        if child.device_node:
                            device_paths.add(child.device_node)
                    for link in device.device_links:
                        device_paths.add(link)
            elif board_id and not usb_vendor_id and not usb_product_id:
                # try with board id alone
                if device.get("ID_SERIAL_SHORT") == board_id:
                    device_paths.add(device.device_node)
                    added.add(board_id)
                    for child in device.children:
                        if child.device_node:
                            device_paths.add(child.device_node)
                    for link in device.device_links:
                        device_paths.add(link)
            elif usb_fs_label:
                # Just restrict by filesystem label.
                if device.get("ID_FS_LABEL") == usb_fs_label:
                    device_paths.add(device.device_node)
                    added.add(usb_fs_label)
                    for child in device.children:
                        if child.device_node:
                            device_paths.add(child.device_node)
                    for link in device.device_links:
                        device_paths.add(link)
    if device_info:
        for static_device in device_info:
            for _, value in static_device.items():
                if value not in added:
                    raise InfrastructureError(
                        "Unable to add all static devices: board_id '%s' was not found"
                        % value)
    if logger and device_paths:
        logger.debug("Adding %s", ", ".join(device_paths))
    return list(device_paths)
Ejemplo n.º 6
0
import os
import re
import subprocess
import logging
import pyudev

from . import util
from .size import Size
from .flags import flags

import gi
gi.require_version("BlockDev", "2.0")

from gi.repository import BlockDev as blockdev

global_udev = pyudev.Context()
log = logging.getLogger("blivet")

ignored_device_names = []
""" device name regexes to ignore; this should be empty by default """


def device_to_dict(device):
    # Transform Device to dictionary
    # Originally it was possible to use directly Device where needed,
    # but it lead to unfixable excessive deprecation warnings from udev.
    # Sice blivet uses Device.properties only (with couple of exceptions)
    # this is a functional workaround. (japokorn May 2017)

    result = dict(device.properties)
    result["SYS_NAME"] = device.sys_name
Ejemplo n.º 7
0
 def test_create(self, device):
     '''
     Make sure the correct device is created
     '''
     name = f'ratbag-emu {device.name} ({self.vid:04x}:{self.pid:04x}, 0)'
     assert list(pyudev.Context().list_devices(subsystem='hid', HID_NAME=name))
Ejemplo n.º 8
0
    def get_dev_model(self):

        context = pyudev.Context()
        udev_model = pyudev.Device.from_device_file(context, self.dev)
        dev_model = udev_model.get('ID_MODEL')
        return dev_model
Ejemplo n.º 9
0
 def execute(self):
     # Check if postfix is running.
     try:
         manager = openmediavault.systemd.Manager()
         unit = manager.get_unit("postfix.service")
         active = unit.active
     except Exception:  # pylint: disable=broad-except
         active = False
     if not active:
         d = dialog.Dialog(dialog="dialog")
         code = d.msgbox(
             "Failed to submit the system diagnostic "
             "report to the administrator account via email because "
             "the email notification service is disabled.",
             backtitle=self.description,
             height=7,
             width=56,
         )
         if code != d.OK:
             return 0
         code = d.yesno(
             "Do you want to copy the system diagnostic "
             "report onto an USB device?",
             backtitle=self.description,
             height=6,
             width=45,
         )
         if code != d.OK:
             return 0
         d.infobox(
             "Please connect the USB device now.",
             backtitle=self.description,
             height=3,
             width=38,
         )
         # Wait until USB device is plugged in.
         context = pyudev.Context()
         monitor = pyudev.Monitor.from_netlink(context)
         monitor.filter_by(subsystem="block", device_type="partition")
         monitor.start()
         for device in iter(monitor.poll, None):
             # Only process 'add' events.
             if device.action != "add":
                 continue
             # Only process partitions with a file systems.
             if not "ID_FS_TYPE" in device:
                 continue
             break
         d.infobox(
             "USB device {} detected. Please wait ...".format(
                 device.get("DEVNAME")),
             backtitle=self.description,
             height=3,
             width=50,
         )
         try:
             mntdir = tempfile.mkdtemp()
             outfile = "{}/sysinfo-{}-{}.txt".format(
                 mntdir, socket.gethostname(), time.strftime("%Y%m%d%H%M"))
             openmediavault.procutils.check_call(
                 ["mount", device.get("DEVNAME"), mntdir])
             with open(outfile, "w") as out:
                 openmediavault.procutils.check_call(["omv-sysinfo"],
                                                     stdout=out)
         except:  # pylint: disable=try-except-raise
             raise
         finally:
             openmediavault.procutils.check_call(
                 ["umount", device.get("DEVNAME")])
             shutil.rmtree(mntdir)
         d.infobox(
             "You can disconnect the USB device now.",
             backtitle=self.description,
             height=3,
             width=42,
         )
     else:
         print("Submitting system diagnostic report to the "
               "administrator account. Please check your email "
               "mailbox ...")
         openmediavault.procutils.check_call([
             "omv-sysinfo",
             "|",
             "mail",
             "-s",
             "System diagnostic report",
             "root",
         ])
     return 0
Ejemplo n.º 10
0
def enumerate_devices():
    global devices
    global enumstate

    t0 = time.monotonic()
    if enumstate == 'init':
        enumstate = {
            'monitor': False,
            'starttime': t0,
            'scantime': 0,
            'retries': 0,
            'pyudevwarning': False
        }
        devices = {}
        read_last_working_devices()

    if enumstate['monitor']:
        # only scan devices if they change
        ret = enumstate['monitor'].poll(0)
        if ret:
            enumstate['scantime'] = t0
            enumstate['retries'] = 5  # up to 5 retries
            while ret:
                debug('serialprobe pyudev monitor', ret)
                ret = enumstate['monitor'].poll(0)  # flush events
        if enumstate['retries'] == 0 or t0 < enumstate['scantime']:
            return False

    else:
        # delay monitor slightly to ensure startup speed
        if t0 > enumstate['starttime'] + 5:
            # try to start pyudev
            import signal
            # need to temporary disable sigchld while loading pyudev
            cursigchld_handler = signal.getsignal(signal.SIGCHLD)
            signal.signal(signal.SIGCHLD, signal.SIG_IGN)
            try:
                import pyudev
                context = pyudev.Context()
                enumstate['monitor'] = pyudev.Monitor.from_netlink(context)
                enumstate['monitor'].filter_by(subsystem='usb')
            except Exception as e:
                # try pyudev/scanning again in 10 seconds if it is delayed loading
                enumstate['starttime'] = time.monotonic() + 10
                if not enumstate['pyudevwarning']:
                    print(_('no pyudev module! will scan usb devices often!'),
                          e)
                    enumstate['pyudevwarning'] = True

            signal.signal(signal.SIGCHLD, cursigchld_handler)

        if t0 < enumstate['scantime']:
            return False
        enumstate['scantime'] = t0 + 20  # scan every 20 seconds

    scanned_devices = scan_devices()
    if enumstate['monitor']:
        prev_devices = {}
        for name in devices:
            prev_devices[name] = {'realpath': devices[name]['realpath']}
        if prev_devices == scanned_devices:  # compare path and realpath
            if enumstate['retries'] > 0:
                enumstate[
                    'scantime'] += 2  #try again in 2 seconds until we get a change
                enumstate['retries'] -= 1
            return False
        elif enumstate['monitor']:
            debug('serialprobe pyudev found it', devices, scanned_devices)
            enumstate['retries'] = 0

    debug('serialprobe scan', scanned_devices)
    # remove devices not scanned
    for device in list(devices):
        if not device in scanned_devices:
            del devices[device]

    # add new devices and set the time the device was added
    for device in scanned_devices:
        if not device in devices:
            devices[device] = scanned_devices[device]
            devices[device]['time'] = t0
    return True
Ejemplo n.º 11
0
 def __registerUdevCallback(self):
     context = pyudev.Context()
     monitor = Monitor.from_netlink(context)
     monitor.filter_by(subsystem='block')
     observer = MonitorObserver(monitor, callback=self.__checkUdevEvent, name='monitor-observer')
     observer.start()
Ejemplo n.º 12
0
 def __init__(self, coresys: CoreSys):
     """Initialize Hardware Monitor object."""
     self.coresys: CoreSys = coresys
     self.context = pyudev.Context()
     self.monitor: Optional[pyudev.Monitor] = None
     self.observer: Optional[pyudev.MonitorObserver] = None
Ejemplo n.º 13
0
    def idisk_get(self):
        """Enumerate disk topology based on:

        :param self
        :returns list of disk and attributes
        """
        idisk = []
        context = pyudev.Context()

        for device in context.list_devices(DEVTYPE='disk'):
            if not utils.is_system_usable_block_device(device):
                continue

            if device['MAJOR'] in constants.VALID_MAJOR_LIST:
                if 'ID_PATH' in device:
                    device_path = "/dev/disk/by-path/" + device['ID_PATH']
                    LOG.debug("[DiskEnum] device_path: %s ", device_path)
                else:
                    # We should always have a udev supplied /dev/disk/by-path
                    # value as a matter of normal operation. We do not expect
                    # this to occur, thus the error.
                    #
                    # The kickstart files for the host install require the
                    # by-path value also to be present or the host install will
                    # fail. Since the installer and the runtime share the same
                    # kernel/udev we should not see this message on an installed
                    # system.
                    device_path = None
                    LOG.error(
                        "Device %s does not have an ID_PATH value provided "
                        "by udev" % device.device_node)

                size_mib = 0
                available_mib = 0
                model_num = ''
                serial_id = ''

                # Can merge all try/except in one block but this allows at
                # least attributes with no exception to be filled
                try:
                    size_mib = utils.get_disk_capacity_mib(device.device_node)
                except Exception as e:
                    self.handle_exception(
                        "Could not retrieve disk size - %s " % e)

                try:
                    available_mib = self.get_disk_available_mib(
                        device_node=device.device_node)
                except Exception as e:
                    self.handle_exception(
                        "Could not retrieve disk %s free space" % e)

                try:
                    # ID_MODEL received from udev is not correct for disks that
                    # are used entirely for LVM. LVM replaced the model ID with
                    # its own identifier that starts with "LVM PV".For this
                    # reason we will attempt to retrieve the correct model ID
                    # by using 2 different commands: hdparm and lsblk and
                    # hdparm. If one of them fails, the other one can attempt
                    # to retrieve the information. Else we use udev.

                    # try hdparm command first
                    hdparm_command = 'hdparm -I %s |grep Model' % (
                        device.get('DEVNAME'))
                    hdparm_process = subprocess.Popen(hdparm_command,
                                                      stdout=subprocess.PIPE,
                                                      shell=True)
                    hdparm_output = hdparm_process.communicate()[0]
                    if hdparm_process.returncode == 0:
                        second_half = hdparm_output.split(':')[1]
                        model_num = second_half.strip()
                    else:
                        # try lsblk command
                        lsblk_command = 'lsblk -dn --output MODEL %s' % (
                            device.get('DEVNAME'))
                        lsblk_process = subprocess.Popen(
                            lsblk_command, stdout=subprocess.PIPE, shell=True)
                        lsblk_output = lsblk_process.communicate()[0]
                        if lsblk_process.returncode == 0:
                            model_num = lsblk_output.strip()
                        else:
                            # both hdparm and lsblk commands failed, try udev
                            model_num = device.get('ID_MODEL')
                    if not model_num:
                        model_num = constants.DEVICE_MODEL_UNKNOWN
                except Exception as e:
                    self.handle_exception("Could not retrieve disk model "
                                          "for disk %s. Exception: %s" %
                                          (device.get('DEVNAME'), e))
                try:
                    if 'ID_SCSI_SERIAL' in device:
                        serial_id = device['ID_SCSI_SERIAL']
                    else:
                        serial_id = device['ID_SERIAL_SHORT']
                except Exception as e:
                    self.handle_exception("Could not retrieve disk "
                                          "serial ID - %s " % e)

                capabilities = dict()
                if model_num:
                    capabilities.update({'model_num': model_num})

                if self.get_rootfs_node() == device.device_node:
                    capabilities.update({'stor_function': 'rootfs'})

                rotational = self.is_rotational(device)
                device_type = device.device_type

                rotation_rate = constants.DEVICE_TYPE_UNDETERMINED
                if rotational == '1':
                    device_type = constants.DEVICE_TYPE_HDD
                    if 'ID_ATA_ROTATION_RATE_RPM' in device:
                        rotation_rate = device['ID_ATA_ROTATION_RATE_RPM']
                elif rotational == '0':
                    if constants.DEVICE_NAME_NVME in device.device_node:
                        device_type = constants.DEVICE_TYPE_NVME
                    else:
                        device_type = constants.DEVICE_TYPE_SSD
                    rotation_rate = constants.DEVICE_TYPE_NA

                # TODO else: what is the other possible stor_function value?
                #      or do we just use pair { 'is_rootfs': True } instead?
                # Obtain device ID and WWN.
                device_id, device_wwn = self.get_device_id_wwn(device)

                attr = {
                    'device_node': device.device_node,
                    'device_num': device.device_number,
                    'device_type': device_type,
                    'device_path': device_path,
                    'device_id': device_id,
                    'device_wwn': device_wwn,
                    'size_mib': size_mib,
                    'available_mib': available_mib,
                    'serial_id': serial_id,
                    'capabilities': capabilities,
                    'rpm': rotation_rate,
                }

                idisk.append(attr)

        LOG.debug("idisk= %s" % idisk)

        return idisk
Ejemplo n.º 14
0
    def run(self):
        context = pyudev.Context()

        #Check the status of the system right now
        # 1. Check if we have any drives connected
        for d in context.list_devices(subsystem='block', DEVTYPE='disk'):
            if d.attributes.asbool('removable'):
                #it's removable media, let's find the partitions
                partitions = list(
                    context.list_devices(subsystem='block',
                                         DEVTYPE='partition',
                                         parent=d))
                for p in partitions:
                    # we only analyze the first one, ignore other partitions
                    #p = partitions[0]

                    #check if the partition is mounted
                    mountPoint = self._findMountPoint(p.device_node)
                    if mountPoint:
                        self._logger.info(
                            'Found mounted removable drive (%s) at %s' %
                            (p.device_node, mountPoint))
                    else:
                        self._logger.info(
                            'Mounting inserted removable drive (%s)' %
                            p.device_node)
                        self._mountPartition(p.device_node,
                                             self._getDeviceMountDirectory(p))

        # 2. Check if there are left over directories with no drives mounted
        for f in glob('%s/*/*' % ROOT_MOUNT_POINT):
            if os.path.isdir(f) and not os.listdir(f):
                #empty directory found, let's see if it's mounted
                if not self._isMounted(f):
                    #Not mounted and empty, delete directory.
                    os.rmdir(f)  #main dir
                    os.rmdir('/'.join(f.split('/')[:-1]))  #uuid dir

        self._mountPoints = None  # We reset here since we don't need it anymore, it will be re-created on shutdown

        # Start listening for events
        self.monitor = pyudev.Monitor.from_netlink(context)
        self.monitor.filter_by(subsystem='block')

        for device in iter(self.monitor.poll, None):

            if self.stopThread:
                self.monitor.stop()
                return

            if device.device_type == 'partition':
                if device.action == 'add':
                    devName = device.device_node
                    self._logger.info('%s pluged in' % devName)
                    mountPath = self._getDeviceMountDirectory(device)
                    if self._mountPartition(devName, mountPath):
                        self._eventManager.fire(Events.EXTERNAL_DRIVE_MOUNTED,
                                                {
                                                    "mount_path": mountPath,
                                                    "device_node": devName
                                                })

                if device.action == 'remove':
                    devName = device.device_node
                    mountPath = self._getDeviceMountDirectory(device)
                    self._logger.info('%s removed' % devName)
                    if self._umountPartition(
                            self._getDeviceMountDirectory(device)):
                        self._eventManager.fire(
                            Events.EXTERNAL_DRIVE_PHISICALLY_REMOVED, {
                                "device_node": devName,
                                "mount_path": mountPath,
                            })
Ejemplo n.º 15
0
License for the specific language governing permissions and limitations
under the License.
'''

import os
import re
import six
import socket
import stat
import subprocess
import uuid
from contextlib import contextmanager

import pyudev

_CONTEXT = pyudev.Context()

class RTSLibError(Exception):
    '''
    Generic rtslib error.
    '''
    pass

class RTSLibALUANotSupported(RTSLibError):
    '''
    Backend does not support ALUA.
    '''
    pass

class RTSLibBrokenLink(RTSLibError):
    '''
Ejemplo n.º 16
0
    def vendorShort(self):
        lv = len(self._vendor)
        lvdb = len(self._vendordb)
        vendor = self._vendor
        if (lvdb > 0) and (lvdb < lv) and (lv > 8):
            vendor = self._vendordb
        return vendor

    def modelShort(self):
        return self._modelenc


devices = dict()

udev = pyudev.Context()

############################################################
# gather devoces
############################################################

for d in udev.list_devices(subsystem="usb"):
    #print(dict(d))
    DEVTYPE = d.get("DEVTYPE")
    if DEVTYPE == "usb_device":  # leaf devices
        busnum = d.attributes.get("busnum")
        devnum = d.attributes.get("devnum")
        devpath = d.attributes.get("devpath")
        pos = "%03d:%03d" % (int(busnum), int(devnum))
        #print(d.sys_name,busnum,devnum,devpath )
        devi = devinfo(pos, pos)
Ejemplo n.º 17
0
    def find_video_device(self):
        """
        Attempts to automatically detect which video device corresponds to the PureThermal Lepton by searching for the PID and VID.

        Returns
        -------
            int
                device number
        """

        res = None

        if sys.platform.startswith('win32'):
            device_check_path = pkg_resources.resource_filename(
                'flirpy', 'bin/find_cameras.exe')
            device_id = int(
                subprocess.check_output([device_check_path,
                                         "PureThermal"]).decode())

            if device_id >= 0:
                return device_id

        elif sys.platform == "darwin":
            output = subprocess.check_output(
                ["system_profiler", "SPCameraDataType"]).decode()
            devices = [
                line.strip() for line in output.decode().split("\n")
                if line.strip().startswith("Model")
            ]

            device_id = 0

            for device in devices:
                if device.contains("VendorID_1E4E") and device.contains(
                        "ProductID_0100"):
                    return device_id

        else:
            import pyudev

            context = pyudev.Context()
            devices = pyudev.Enumerator(context)

            path = "/sys/class/video4linux/"
            video_devices = [
                os.path.join(path, device) for device in os.listdir(path)
            ]
            dev = []
            for device in video_devices:
                udev = pyudev.Devices.from_path(context, device)

                try:
                    vid = udev.properties['ID_VENDOR_ID']
                    pid = udev.properties['ID_MODEL_ID']

                    if vid.lower() == "1e4e" and pid.lower() == "0100":
                        dev.append(int(device.split('video')[-1]))
                except KeyError:
                    pass

            # For some reason multiple devices can show up
            if len(dev) > 1:
                for d in dev:
                    cam = cv2.VideoCapture(d + cv2.CAP_V4L2)
                    data = cam.read()
                    cam.release()

                    if data[0] == True and data[1] is not None:
                        res = d
                        break
            elif len(dev) == 1:
                res = dev[0]

        return res
Ejemplo n.º 18
0
 def __init__(self):
     super(USBDetector, self).__init__()
     self.mouse_online = False
     self.context = pyudev.Context()
     self.monitor = pyudev.Monitor.from_netlink(self.context)
     self.monitor.filter_by(subsystem="usb")
Ejemplo n.º 19
0
import pyudev
import evdev
import functools
import re

context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem='input')

monitor.start()


def kbdIden():
    target_device_data = []  #list to store recieved data about device
    for device in iter(functools.partial(monitor.poll, 0), None):
        #print ('{0.action} on {0.device_path}'.format(device))

        target_device_data.append(device.device_path)  #data collection
        try:
            if device.action == "add":
                for dev in target_device_data:
                    splitted = dev.split('/')
                    target = splitted[-1]
                    if re.match('event[0-9+]',
                                target):  #check of event.. param.
                        added_dev = str(
                            evdev.InputDevice(
                                '/dev/input/{0}'.format(target))).split(
                                    '/')  #data collection about target device
                        #print (added_dev)
                        #re_addded_dev  = re.findall('.*name ".* Keyboard".*', added_dev[3])
Ejemplo n.º 20
0
  def execute(self):
      # Default values.
      address = ""
      netmask = ""
      gateway = ""
      method = "dhcp"
      address6 = ""
      method6 = "manual"
      netmask6 = 64
      gateway6 = ""
      wol = False
      dns_nameservers = ""
      wpa_ssid = None
      wpa_psk = None
      rpc_method = "setEthernetIface"
      rpc_params = {}
      # Get the network interface device.
      devices = []
      context = pyudev.Context()
      for device in context.list_devices(subsystem="net"):
          # Skip unwanted network interface devices.
          if device.sys_name in ("lo"):
              continue
          if device.device_type and device.device_type in ("bond"):
              continue
          # Append the network interface name for later use.
          devices.append(device.sys_name)
      devices = natsort.humansorted(devices)
      choices = []
      for idx, sys_name in enumerate(devices):
          device = pyudev.Device.from_name(context, "net", sys_name)
          for id in ["ID_MODEL_FROM_DATABASE", "ID_VENDOR_FROM_DATABASE"]:
              if not id in device:
                  continue
              choices.append([
                  sys_name,
                  openmediavault.string.truncate(device[id], 50)
              ])
              break
      d = dialog.Dialog(dialog="dialog")
      (code, tag) = d.menu("Please select a network interface. Note, the " \
 "existing network interface configuration will be deleted.",
      backtitle=self.description, clear=True,
      height=14, width=70, menu_height=6, choices=choices)
      if code in (d.CANCEL, d.ESC):
          return 0
      device_name = tag
      # Use DHCP?
      code = d.yesno(
          "Do you want to use DHCPv4 for this interface?",
          backtitle=self.description,
          height=5,
          width=49
      )
      if code == d.ESC:
          return 0
      if code != d.OK:
          address = None
          netmask = None
          gateway = None
          method = "static"
          # Get the static IPv4 address.
          while not address:
              (code, address) = d.inputbox(
                  "Please enter the IPv4 address.",
                  backtitle=self.description,
                  clear=True,
                  height=8,
                  width=60,
                  init=""
              )
              if code != d.OK:
                  return 0
              if not address:
                  d.msgbox(
                      "The field must not be empty.",
                      backtitle=self.description,
                      height=5,
                      width=32
                  )
                  continue
              try:
                  ipaddress.ip_address(address)
              except Exception as e:
                  address = None
                  d.msgbox(
                      "Please enter a valid IPv4 address.",
                      backtitle=self.description,
                      height=5,
                      width=38
                  )
                  continue
          # Get the IPv4 netmask.
          while not netmask:
              (code, netmask) = d.inputbox(
                  "Please enter the IPv4 netmask.",
                  backtitle=self.description,
                  clear=True,
                  height=8,
                  width=60,
                  init=""
              )
              if code != d.OK:
                  return 0
              if not netmask:
                  d.msgbox(
                      "The field must not be empty.",
                      backtitle=self.description,
                      height=5,
                      width=32
                  )
                  continue
              try:
                  ipaddress.ip_address(netmask)
              except Exception:
                  netmask = None
                  d.msgbox(
                      "Please enter a valid netmask.",
                      backtitle=self.description,
                      height=5,
                      width=33
                  )
                  continue
          # Get default IPv4 gateway.
          while not gateway:
              (code, gateway) = d.inputbox(
                  "Please enter the default IPv4 gateway.",
                  backtitle=self.description,
                  clear=True,
                  height=8,
                  width=60,
                  init=""
              )
              if code != d.OK:
                  return 0
              try:
                  ipaddress.ip_address(gateway)
              except Exception:
                  gateway = None
                  d.msgbox(
                      "Please enter a valid gateway.",
                      backtitle=self.description,
                      height=5,
                      width=33
                  )
                  continue
      # Use IPv6?
      code = d.yesno(
          "Do you want to configure IPv6 for this interface?",
          backtitle=self.description,
          height=5,
          width=53,
          defaultno=True
      )
      if code == d.ESC:
          return 0
      if code == d.OK:
          # Use stateful address autoconfiguration (DHCPv6)?
          code = d.yesno("Do you want to enable stateful address " \
  "autoconfiguration (DHCPv6)?",
          backtitle=self.description,
          height=6, width=42)
          if code == d.ESC:
              return 0
          if code == d.OK:
              method6 = "dhcp"
          else:
              # Use stateless address autoconfiguration (SLAAC)?
              code = d.yesno("Do you want to enable stateless address " \
   "autoconfiguration (SLAAC)?",
              backtitle=self.description,
              height=6, width=42)
              if code == d.ESC:
                  return 0
              if code == d.OK:
                  method6 = "auto"
              else:
                  method6 = "static"
              # Get static IPv6 address.
              address6 = None
              while not address6:
                  (code, address6) = d.inputbox(
                      "Please enter the IPv6 address.",
                      backtitle=self.description,
                      clear=True,
                      height=8,
                      width=60,
                      init=""
                  )
                  if code != d.OK:
                      return 0
                  if not address6:
                      d.msgbox(
                          "The field must not be empty.",
                          backtitle=self.description,
                          height=5,
                          width=32
                      )
                      continue
                  try:
                      ipaddress.ip_address(address6)
                  except Exception:
                      address6 = None
                      d.msgbox(
                          "Please enter a valid IPv6 address.",
                          backtitle=self.description,
                          height=5,
                          width=38
                      )
                      continue
              # Get the prefix length.
              netmask6 = None
              while not netmask6:
                  (code, netmask6) = d.inputbox(
                      "Please enter the IPv6 prefix length.",
                      backtitle=self.description,
                      clear=True,
                      height=8,
                      width=64,
                      init="64"
                  )
                  if code != d.OK:
                      return 0
                  if not netmask6:
                      d.msgbox(
                          "The field must not be empty.",
                          backtitle=self.description,
                          height=5,
                          width=32
                      )
                      continue
                  if int(netmask6) < 0 or int(netmask6) > 128:
                      netmask6 = None
                      d.msgbox(
                          "Please enter a valid netmask.",
                          backtitle=self.description,
                          height=5,
                          width=33
                      )
                      continue
              # Get default IPv6 gateway.
              gateway6 = None
              while not gateway6:
                  (code, gateway6) = d.inputbox(
                      "Please enter the default IPv6 gateway.",
                      backtitle=self.description,
                      clear=True,
                      height=8,
                      width=60,
                      init=""
                  )
                  if code != d.OK:
                      return 0
                  try:
                      ipaddress.ip_address(gateway6)
                  except Exception:
                      gateway6 = None
                      d.msgbox(
                          "Please enter a valid gateway.",
                          backtitle=self.description,
                          height=5,
                          width=33
                      )
                      continue
      # Get the DNS name servers. Note, only one IP address is
      # supported here.
      if method == "static" or method6 == "static":
          while True:
              (code, dns_nameservers) = d.inputbox(
              "Please enter the DNS name server. If you don't want " \
   "to use any name server, just leave this field blank.",
              backtitle=self.description,
              clear=True, height=8, width=60, init="")
              if code != d.OK:
                  return 0
              if not dns_nameservers:
                  break
              try:
                  ipaddress.ip_address(dns_nameservers)
                  break
              except Exception:
                  dns_nameservers = ""
                  d.msgbox(
                      "Please enter a valid IP address.",
                      backtitle=self.description,
                      height=5,
                      width=30
                  )
      # Enable WOL?
      code = d.yesno(
          "Do you want to enable WOL for this interface?",
          backtitle=self.description,
          height=5,
          width=50,
          defaultno=True
      )
      if code == d.ESC:
          return 0
      if code == d.OK:
          wol = True
      # Set the default RPC parameters.
      rpc_params.update({
          "uuid": openmediavault.getenv("OMV_CONFIGOBJECT_NEW_UUID"),
          "devicename": device_name,
          "method": method,
          "address": address,
          "netmask": netmask,
          "gateway": gateway,
          "method6": method6,
          "address6": address6,
          "netmask6": netmask6,
          "gateway6": gateway6,
          "dnsnameservers": dns_nameservers,
          "dnssearch": "",
          "mtu": 0,
          "wol": wol,
          "comment": "",
      })
      # Do we process a wireless network interface?
      if re.match(r"^wlan[0-9]+$", device_name):
          rpc_method = "setWirelessIface"
          # Get the SSID.
          while not wpa_ssid:
              (code, wpa_ssid) = d.inputbox(
                  "Please enter the name of the wireless network (SSID).",
                  backtitle=self.description,
                  clear=True,
                  height=8,
                  width=60,
                  init=""
              )
              if code != d.OK:
                  return 0
              if not wpa_ssid:
                  d.msgbox(
                      "The field must not be empty.",
                      backtitle=self.description,
                      height=5,
                      width=32
                  )
          rpc_params["wpassid"] = wpa_ssid
          # Get the pre-shared key.
          while not wpa_psk:
              (code, wpa_psk) = d.inputbox(
                  "Please enter the pre-shared key (PSK).",
                  backtitle=self.description,
                  clear=True,
                  height=8,
                  width=45,
                  init=""
              )
              if code != d.OK:
                  return 0
              if not wpa_psk:
                  d.msgbox(
                      "The field must not be empty.",
                      backtitle=self.description,
                      height=5,
                      width=32
                  )
          rpc_params["wpapsk"] = wpa_psk
      # Update the interface configuration.
      print("Configuring network interface. Please wait ...")
      # Delete all existing network interface configuration objects.
      interfaces = openmediavault.rpc.call(
          "Network", "enumerateConfiguredDevices"
      )
      for interface in interfaces:
          openmediavault.rpc.call(
              "Network", "deleteInterface", {"uuid": interface["uuid"]}
          )
      # Insert a new network interface configuration object.
      openmediavault.rpc.call("Network", rpc_method, rpc_params)
      openmediavault.rpc.call(
          "Config", "applyChanges", {
              "modules": [],
              "force": False
          }
      )
      print("The network interface configuration was successfully changed.")
      return 0
Ejemplo n.º 21
0
def usb_keyboard_present():
    context = pyudev.Context()
    keyboards = context.list_devices(subsystem='input', ID_INPUT_KEYBOARD='1')
    return any([d.get('ID_USB_INTERFACES', False) for d in keyboards])
Ejemplo n.º 22
0
def details_udev(usb_disk_part):
    """
    Get details of USB partition using udev
    """
    assert usb_disk_part is not None
    assert platform.system() == "Linux"

    try:
        import pyudev
    except:
        from . import pyudev


#   Try with PyUdev to get the details of USB disks.
#   This is the easiest and reliable method to find USB details.
#   Also, it is a standalone package and no dependencies are required.
    context = pyudev.Context()
    try:
        device = pyudev.Device.from_device_file(context, usb_disk_part)
    except:
        gen.log("ERROR: Unknown disk/partition (%s)" % str(usb_disk_part))
        return None

    fdisk_cmd_out = subprocess.check_output('fdisk -l ' + usb_disk_part,
                                            shell=True)

    if b'Extended' in fdisk_cmd_out:
        mount_point = ''
        uuid = ''
        file_system = ''
        vendor = ''
        model = ''
        label = ''
        devtype = "extended partition"

    elif device.get('DEVTYPE') == "partition":
        uuid = device.get('ID_FS_UUID') or ""
        file_system = device.get('ID_FS_TYPE') or ""
        label = device.get('ID_FS_LABEL') or ""
        mount_point = u.mount(usb_disk_part) or ""
        mount_point = mount_point.replace('\\x20', ' ')
        vendor = device.get('ID_VENDOR') or ""
        model = device.get('ID_MODEL') or ""
        devtype = "partition"

    elif device.get('DEVTYPE') == "disk":
        mount_point = ""
        uuid = ""
        file_system = ""
        label = device.get('ID_FS_LABEL') or ""
        vendor = device.get('ID_VENDOR') or ""
        model = device.get('ID_MODEL') or ""
        devtype = "disk"

    if mount_point not in ["", "None"]:
        size_total = shutil.disk_usage(mount_point)[0]
        size_used = shutil.disk_usage(mount_point)[1]
        size_free = shutil.disk_usage(mount_point)[2]

    else:
        fdisk_cmd = 'fdisk -l ' + usb_disk_part + ' | grep "^Disk /" | sed -re "s/.*\s([0-9]+)\sbytes.*/\\1/"'
        size_total = subprocess.check_output(fdisk_cmd, shell=True).strip()
        size_used = ""
        size_free = ""
        mount_point = ""

    return {
        'uuid': uuid,
        'file_system': file_system,
        'label': label,
        'mount_point': mount_point,
        'size_total': size_total,
        'size_used': size_used,
        'size_free': size_free,
        'vendor': vendor,
        'model': model,
        'devtype': devtype
    }
Ejemplo n.º 23
0
 def __init__(self, results={}):
     self.results = results
     self.context = pyudev.Context()
Ejemplo n.º 24
0
def test_export_firmware_extended_fedora29(C):
    """
    Check, whether the firmware file is exported correctly, and in correct size.
    Apparently, the auto-remounting side effect of the v0.46 change, is disturbing the export process.
    Unmounting the UV just before the export gives the device 20/20 success rate.
    Test case for issue https://github.com/Nitrokey/nitrokey-app/issues/399
    """

    skip_if_device_version_lower_than({'S': 43})
    skip_if_not_fedora('Tested on Fedora only. To check on other distros.')

    from time import sleep
    import os
    from os.path import exists as exist
    import re
    try:
        import pyudev as pu
        import pexpect
    except:
        pytest.skip(
            'Skipping due to missing required packages: pyudev and pexpect.')

    ctx = pu.Context()
    devices = ctx.list_devices(subsystem='block', ID_VENDOR='Nitrokey')
    device = None
    for d in devices:
        if d.device_type == 'partition':
            device = '/dev/{}'.format(d.sys_name)
            break
    assert device, 'Device could not be found'

    pexpect.run(f'udisksctl unmount -b {device}').decode()
    sleep(1)
    _res = pexpect.run(f'udisksctl mount -b {device}').decode()
    firmware_abs_path = re.findall('at (/.*)\.', _res)
    assert firmware_abs_path, 'Cannot get mount point'
    firmware_abs_path = firmware_abs_path[0]

    print('path: {}, device: {}'.format(firmware_abs_path, device))
    assert firmware_abs_path, 'Cannot get mount point'
    firmware_abs_path = firmware_abs_path + '/firmware.bin'

    checks = 0
    checks_add = 0

    if exist(firmware_abs_path):
        os.remove(firmware_abs_path)

    assert not exist(firmware_abs_path)

    ATTEMPTS = 20
    for i in range(ATTEMPTS):
        # if umount is disabled, success rate is 3/10, enabled: 10/10
        pexpect.run(f'udisksctl unmount -b {device}')
        assert C.NK_export_firmware(
            DefaultPasswords.ADMIN) == DeviceErrorCode.STATUS_OK
        pexpect.run(f'udisksctl mount -b {device}')
        sleep(1)
        firmware_file_exist = exist(firmware_abs_path)
        if firmware_file_exist:
            checks += 1
            getsize = os.path.getsize(firmware_abs_path)
            print('Firmware file exist, size: {}'.format(getsize))
            checks_add += 1 if getsize >= 100 * 1024 else 0
            # checks_add += 1 if os.path.getsize(firmware_abs_path) == 256*1024 else 0
            os.remove(firmware_abs_path)
        assert not exist(firmware_abs_path)

    print('CHECK {} ; CHECK ADDITIONAL {}'.format(checks, checks_add))

    assert checks == ATTEMPTS
    assert checks_add == checks