Python stat.S_ISBLK Examples

The following are 30 code examples of stat.S_ISBLK(). 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 stat , or try the search function .
Example #1
Source File: usb.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def is_block(usb_disk):
    """
    Function to detect if the USB is block device
    :param usb_disk: USB disk path
    :return: True is devie is block device else False
    """
    import stat
    if platform.system() == 'Linux':
        if len(usb_disk) != 9:
            return False
    elif platform.system() == 'Windows':
        if len(usb_disk) != 2:
            return False
        else:
            return True
    try:
        mode = os.stat(usb_disk).st_mode
        gen.log(mode)
        gen.log(stat.S_ISBLK(mode))
    except:
        return False

    return stat.S_ISBLK(mode) 
Example #2
Source File: filegenerator.py    From bash-lambda-layer with MIT License 6 votes vote down vote up
def is_special_file(path):
    """
    This function checks to see if a special file.  It checks if the
    file is a character special device, block special device, FIFO, or
    socket.
    """
    mode = os.stat(path).st_mode
    # Character special device.
    if stat.S_ISCHR(mode):
        return True
    # Block special device
    if stat.S_ISBLK(mode):
        return True
    # FIFO.
    if stat.S_ISFIFO(mode):
        return True
    # Socket.
    if stat.S_ISSOCK(mode):
        return True
    return False 
Example #3
Source File: disk_utils.py    From ironic-lib with Apache License 2.0 6 votes vote down vote up
def is_block_device(dev):
    """Check whether a device is block or not."""
    attempts = CONF.disk_utils.partition_detection_attempts
    for attempt in range(attempts):
        try:
            s = os.stat(dev)
        except OSError as e:
            LOG.debug("Unable to stat device %(dev)s. Attempt %(attempt)d "
                      "out of %(total)d. Error: %(err)s",
                      {"dev": dev, "attempt": attempt + 1,
                       "total": attempts, "err": e})
            time.sleep(1)
        else:
            return stat.S_ISBLK(s.st_mode)
    msg = _("Unable to stat device %(dev)s after attempting to verify "
            "%(attempts)d times.") % {'dev': dev, 'attempts': attempts}
    LOG.error(msg)
    raise exception.InstanceDeployFailure(msg) 
Example #4
Source File: __init__.py    From hddfancontrol with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, id, pwm_filepath, start_value, stop_value):
    assert(0 <= start_value <= 255)
    assert(0 <= stop_value <= 255)
    self.id = id
    self.pwm_filepath = pwm_filepath
    if stat.S_ISBLK(os.stat(self.pwm_filepath).st_mode):
      # we don't want to write to a block device in setPwmValue
      # command line parameters have probably been mixed up
      raise RuntimeError("%s is a block device, PWM /sys file expected" % (self.pwm_filepath))
    pwm_num = int(__class__.LAST_DIGITS_REGEX.search(self.pwm_filepath).group(1))
    self.fan_input_filepath = os.path.join(os.path.dirname(self.pwm_filepath),
                                           "fan%u_input" % (pwm_num))
    self.enable_filepath = "%s_enable" % (self.pwm_filepath)
    self.start_value = start_value
    self.stop_value = stop_value
    self.startup = False
    self.logger = logging.getLogger("Fan #%u" % (self.id)) 
Example #5
Source File: plugin.py    From phpsploit with GNU General Public License v3.0 6 votes vote down vote up
def mode_filetype(mode):
    mode = stat.S_IFMT(mode)
    dic = {
            stat.S_ISFIFO: "fifo file",
            stat.S_ISCHR: "character device",
            stat.S_ISDIR: "directory",
            stat.S_ISBLK: "block device",
            stat.S_ISREG: "regular file",
            stat.S_ISLNK: "symbolic link",
            stat.S_ISSOCK: "socket",
            stat.S_ISDOOR: "door",
            }
    for test_func, name in dic.items():
        if test_func(mode):
            return name
    return "???" 
Example #6
Source File: _util.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def get_device_type(filename):
    """
    Get the device type of a device file.

    ``filename`` is a string containing the path of a device file.

    Return ``'char'`` if ``filename`` is a character device, or ``'block'`` if
    ``filename`` is a block device.  Raise :exc:`~exceptions.ValueError` if
    ``filename`` is no device file at all.  Raise
    :exc:`~exceptions.EnvironmentError` if ``filename`` does not exist or if
    its metadata was inaccessible.

    .. versionadded:: 0.15
    """
    mode = os.stat(filename).st_mode
    if stat.S_ISCHR(mode):
        return 'char'
    elif stat.S_ISBLK(mode):
        return 'block'
    else:
        raise ValueError('not a device file: {0!r}'.format(filename)) 
Example #7
Source File: utils.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def __hashEntry(self, prefix, entry, s):
        if stat.S_ISREG(s.st_mode):
            digest = self.__index.check(prefix, entry, s, hashFile)
        elif stat.S_ISDIR(s.st_mode):
            digest = self.__hashDir(prefix, entry)
        elif stat.S_ISLNK(s.st_mode):
            digest = self.__index.check(prefix, entry, s, DirHasher.__hashLink)
        elif stat.S_ISBLK(s.st_mode) or stat.S_ISCHR(s.st_mode):
            digest = struct.pack("<L", s.st_rdev)
        elif stat.S_ISFIFO(s.st_mode):
            digest = b''
        else:
            digest = b''
            logging.getLogger(__name__).warning("Unknown file: %s", entry)

        return digest 
Example #8
Source File: UnpackParser.py    From binaryanalysis-ng with GNU Affero General Public License v3.0 5 votes vote down vote up
def unpack(self):
        files_and_labels = []
        pos = 0
        for e in self.data.entries:
            out_labels = []
            if e.filename != self.data.trailing_filename:
                file_path = pathlib.Path(e.filename)
                if file_path.is_absolute():
                    file_path = file_path.relative_to('/')
                mode = e.header.cpio_mode
                outfile_rel = self.rel_unpack_dir / file_path
                if stat.S_ISDIR(mode):
                    self.unpack_directory(outfile_rel)
                elif stat.S_ISLNK(mode):
                    self.unpack_link(file_path, e.filedata.decode())
                    out_labels.append('symbolic link')
                elif stat.S_ISCHR(mode) or stat.S_ISBLK(mode):
                    self.unpack_device(outfile_rel)
                    continue
                elif stat.S_ISREG(mode):
                    filedata_start = e.header.hsize + e.header.nsize + e.header.npaddingsize
                    self.unpack_regular(outfile_rel,
                            pos + filedata_start, e.header.fsize)

                out_labels.append('unpacked')
                files_and_labels.append( (str(self.rel_unpack_dir / file_path), out_labels) )
            pos += e.header.bsize
        return files_and_labels 
Example #9
Source File: pathlib.py    From click-configfile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_block_device(self):
        """
        Whether this path is a block device.
        """
        try:
            return S_ISBLK(self.stat().st_mode)
        except OSError as e:
            if e.errno != ENOENT:
                raise
            # Path doesn't exist or is a broken symlink
            # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
            return False 
Example #10
Source File: utils.py    From AWS-Transit-Gateway-Demo-MultiAccount with MIT License 5 votes vote down vote up
def is_special_file(cls, filename):
        """Checks to see if a file is a special UNIX file.

        It checks if the file is a character special device, block special
        device, FIFO, or socket.

        :param filename: Name of the file

        :returns: True if the file is a special file. False, if is not.
        """
        # If it does not exist, it must be a new file so it cannot be
        # a special file.
        if not os.path.exists(filename):
            return False
        mode = os.stat(filename).st_mode
        # Character special device.
        if stat.S_ISCHR(mode):
            return True
        # Block special device
        if stat.S_ISBLK(mode):
            return True
        # Named pipe / FIFO
        if stat.S_ISFIFO(mode):
            return True
        # Socket.
        if stat.S_ISSOCK(mode):
            return True
        return False 
Example #11
Source File: utils.py    From AWS-Transit-Gateway-Demo-MultiAccount with MIT License 5 votes vote down vote up
def is_special_file(cls, filename):
        """Checks to see if a file is a special UNIX file.

        It checks if the file is a character special device, block special
        device, FIFO, or socket.

        :param filename: Name of the file

        :returns: True if the file is a special file. False, if is not.
        """
        # If it does not exist, it must be a new file so it cannot be
        # a special file.
        if not os.path.exists(filename):
            return False
        mode = os.stat(filename).st_mode
        # Character special device.
        if stat.S_ISCHR(mode):
            return True
        # Block special device
        if stat.S_ISBLK(mode):
            return True
        # Named pipe / FIFO
        if stat.S_ISFIFO(mode):
            return True
        # Socket.
        if stat.S_ISSOCK(mode):
            return True
        return False 
Example #12
Source File: utils.py    From aws-extender with MIT License 5 votes vote down vote up
def is_special_file(cls, filename):
        """Checks to see if a file is a special UNIX file.

        It checks if the file is a character special device, block special
        device, FIFO, or socket.

        :param filename: Name of the file

        :returns: True if the file is a special file. False, if is not.
        """
        # If it does not exist, it must be a new file so it cannot be
        # a special file.
        if not os.path.exists(filename):
            return False
        mode = os.stat(filename).st_mode
        # Character special device.
        if stat.S_ISCHR(mode):
            return True
        # Block special device
        if stat.S_ISBLK(mode):
            return True
        # Named pipe / FIFO
        if stat.S_ISFIFO(mode):
            return True
        # Socket.
        if stat.S_ISSOCK(mode):
            return True
        return False 
Example #13
Source File: pathlib.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def is_block_device(self):
        """
        Whether this path is a block device.
        """
        try:
            return S_ISBLK(self.stat().st_mode)
        except OSError as e:
            if e.errno != ENOENT:
                raise
            # Path doesn't exist or is a broken symlink
            # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
            return False 
Example #14
Source File: loop.py    From osbuild with Apache License 2.0 5 votes vote down vote up
def __init__(self, minor, dir_fd=None):
        """
        Parameters
        ----------
        minor
            the minor number of the underlying device
        dir_fd : int, optional
            A directory file descriptor to a filesystem containing the
            underlying device node, or None to use /dev (default is None)

        Raises
        ------
        UnexpectedDevice
            If the file in the expected device node location is not the
            expected device node
        """

        self.devname = f"loop{minor}"
        self.minor = minor

        with contextlib.ExitStack() as stack:
            if not dir_fd:
                dir_fd = os.open("/dev", os.O_DIRECTORY)
                stack.callback(lambda: os.close(dir_fd))
            self.fd = os.open(self.devname, os.O_RDWR, dir_fd=dir_fd)

        info = os.stat(self.fd)
        if ((not stat.S_ISBLK(info.st_mode)) or
                (not os.major(info.st_rdev) == self.LOOP_MAJOR) or
                (not os.minor(info.st_rdev) == minor)):
            raise UnexpectedDevice(minor, info.st_rdev, info.st_mode) 
Example #15
Source File: pathlib.py    From android_universal with MIT License 5 votes vote down vote up
def is_block_device(self):
        """
        Whether this path is a block device.
        """
        try:
            return S_ISBLK(self.stat().st_mode)
        except OSError as e:
            if not _ignore_error(e):
                raise
            # Path doesn't exist or is a broken symlink
            # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
            return False 
Example #16
Source File: losetup.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def is_loop(filename):
    """Check whether specified filename is a loop device."""
    st = os.stat(filename)
    return stat.S_ISBLK(st.st_mode) and (_major(st.st_rdev) == LOOPMAJOR) 
Example #17
Source File: pathlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def is_block_device(self):
        """
        Whether this path is a block device.
        """
        try:
            return S_ISBLK(self.stat().st_mode)
        except OSError as e:
            if e.errno not in (ENOENT, ENOTDIR):
                raise
            # Path doesn't exist or is a broken symlink
            # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
            return False 
Example #18
Source File: ScanJob.py    From binaryanalysis-ng with GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_block_device(self):
        r = stat.S_ISBLK(self.stat.st_mode)
        if r: self.type = 'block device'
        return r 
Example #19
Source File: utils.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def is_special_file(cls, filename):
        """Checks to see if a file is a special UNIX file.

        It checks if the file is a character special device, block special
        device, FIFO, or socket.

        :param filename: Name of the file

        :returns: True if the file is a special file. False, if is not.
        """
        # If it does not exist, it must be a new file so it cannot be
        # a special file.
        if not os.path.exists(filename):
            return False
        mode = os.stat(filename).st_mode
        # Character special device.
        if stat.S_ISCHR(mode):
            return True
        # Block special device
        if stat.S_ISBLK(mode):
            return True
        # Named pipe / FIFO
        if stat.S_ISFIFO(mode):
            return True
        # Socket.
        if stat.S_ISSOCK(mode):
            return True
        return False 
Example #20
Source File: pathlib.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def is_block_device(self):
        """
        Whether this path is a block device.
        """
        try:
            return S_ISBLK(self.stat().st_mode)
        except OSError as e:
            if not _ignore_error(e):
                raise
            # Path doesn't exist or is a broken symlink
            # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
            return False 
Example #21
Source File: Mime.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_type(path, follow=True, name_pri=100):
    """Returns type of file indicated by path.
    
    path :
      pathname to check (need not exist)
    follow :
      when reading file, follow symbolic links
    name_pri :
      Priority to do name matches.  100=override magic
    
    This tries to use the contents of the file, and falls back to the name. It
    can also handle special filesystem objects like directories and sockets.
    """
    update_cache()
    
    try:
        if follow:
            st = os.stat(path)
        else:
            st = os.lstat(path)
    except:
        t = get_type_by_name(path)
        return t or text

    if stat.S_ISREG(st.st_mode):
        t = get_type_by_contents(path, min_pri=name_pri)
        if not t: t = get_type_by_name(path)
        if not t: t = get_type_by_contents(path, max_pri=name_pri)
        if t is None:
            if stat.S_IMODE(st.st_mode) & 0o111:
                return app_exe
            else:
                return text
        return t
    elif stat.S_ISDIR(st.st_mode): return inode_dir
    elif stat.S_ISCHR(st.st_mode): return inode_char
    elif stat.S_ISBLK(st.st_mode): return inode_block
    elif stat.S_ISFIFO(st.st_mode): return inode_fifo
    elif stat.S_ISLNK(st.st_mode): return inode_symlink
    elif stat.S_ISSOCK(st.st_mode): return inode_socket
    return inode_door 
Example #22
Source File: __init__.py    From hddfancontrol with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, device_filepath, hddtemp_daemon_port, min_temp, max_temp, use_smartctl):
    assert(stat.S_ISBLK(os.stat(device_filepath).st_mode))
    self.device_filepath = __class__.normalizeDrivePath(device_filepath)
    self.stat_filepath = "/sys/block/%s/stat" % (os.path.basename(self.device_filepath))
    self.hddtemp_daemon_port = hddtemp_daemon_port
    self.min_temp = min_temp
    self.max_temp = max_temp
    self.pretty_name = self.getPrettyName()
    self.logger = logging.getLogger(str(self))
    self.supports_hitachi_temp_query = self.supportsHitachiTempQuery()
    self.supports_sct_temp_query = self.supportsSctTempQuery()
    self.use_smartctl = use_smartctl 
Example #23
Source File: rpm.py    From crypto-detector with Apache License 2.0 5 votes vote down vote up
def isblk(self):
        return stat.S_ISBLK(self.mode) 
Example #24
Source File: rpm.py    From crypto-detector with Apache License 2.0 5 votes vote down vote up
def isdev(self):
        return (stat.S_ISCHR(self.mode) or stat.S_ISBLK(self.mode))
# class CpioInfo 
Example #25
Source File: pcachefs.py    From pcachefs with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        v = vars(self)
        v['is_dir'] = stat.S_ISDIR(v['st_mode'])
        v['is_char_dev'] = stat.S_ISCHR(v['st_mode'])
        v['is_block_dev'] = stat.S_ISBLK(v['st_mode'])
        v['is_file'] = stat.S_ISREG(v['st_mode'])
        v['is_fifo'] = stat.S_ISFIFO(v['st_mode'])
        v['is_symlk'] = stat.S_ISLNK(v['st_mode'])
        v['is_sock'] = stat.S_ISSOCK(v['st_mode'])
        return pformat(v) 
Example #26
Source File: pathlib.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_block_device(self):
        """
        Whether this path is a block device.
        """
        try:
            return S_ISBLK(self.stat().st_mode)
        except OSError as e:
            if e.errno not in _IGNORED_ERROS:
                raise
            # Path doesn't exist or is a broken symlink
            # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
            return False 
Example #27
Source File: device_utils_test.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testStatDirectory_fileModes(self):
    expected_modes = (
      ('some_dir', stat.S_ISDIR),
      ('some_file', stat.S_ISREG),
      ('lnk', stat.S_ISLNK),
      ('a_socket1', stat.S_ISSOCK),
      ('block_dev', stat.S_ISBLK),
      ('random', stat.S_ISCHR),
    )
    entries = self.getStatEntries()
    for filename, check in expected_modes:
      self.assertTrue(check(entries[filename]['st_mode'])) 
Example #28
Source File: __init__.py    From OpenMTC with Eclipse Public License 1.0 5 votes vote down vote up
def isdev(self):
		from stat import S_ISBLK, S_ISCHR
		mode = self.__st_mode()
		return S_ISBLK(mode) or S_ISCHR(mode) 
Example #29
Source File: __init__.py    From OpenMTC with Eclipse Public License 1.0 5 votes vote down vote up
def isblockdev(self):
		from stat import S_ISBLK
		return S_ISBLK(self.__st_mode()) 
Example #30
Source File: utils.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def is_special_file(cls, filename):
        """Checks to see if a file is a special UNIX file.

        It checks if the file is a character special device, block special
        device, FIFO, or socket.

        :param filename: Name of the file

        :returns: True if the file is a special file. False, if is not.
        """
        # If it does not exist, it must be a new file so it cannot be
        # a special file.
        if not os.path.exists(filename):
            return False
        mode = os.stat(filename).st_mode
        # Character special device.
        if stat.S_ISCHR(mode):
            return True
        # Block special device
        if stat.S_ISBLK(mode):
            return True
        # Named pipe / FIFO
        if stat.S_ISFIFO(mode):
            return True
        # Socket.
        if stat.S_ISSOCK(mode):
            return True
        return False