Python stat.S_IMODE Examples

The following are 30 code examples of stat.S_IMODE(). 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: shutil.py    From BinderFilter with MIT License 6 votes vote down vote up
def copystat(src, dst):
    """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError, why:
            for err in 'EOPNOTSUPP', 'ENOTSUP':
                if hasattr(errno, err) and why.errno == getattr(errno, err):
                    break
            else:
                raise 
Example #2
Source File: install.py    From web2board with GNU Lesser General Public License v3.0 6 votes vote down vote up
def copyFunc(dest, source, env):
    """Install a source file or directory into a destination by copying,
    (including copying permission/mode bits)."""

    if os.path.isdir(source):
        if os.path.exists(dest):
            if not os.path.isdir(dest):
                raise SCons.Errors.UserError("cannot overwrite non-directory `%s' with a directory `%s'" % (str(dest), str(source)))
        else:
            parent = os.path.split(dest)[0]
            if not os.path.exists(parent):
                os.makedirs(parent)
        scons_copytree(source, dest)
    else:
        shutil.copy2(source, dest)
        st = os.stat(source)
        os.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)

    return 0

#
# Functions doing the actual work of the InstallVersionedLib Builder.
# 
Example #3
Source File: install.py    From web2board with GNU Lesser General Public License v3.0 6 votes vote down vote up
def copyFuncVersionedLib(dest, source, env):
    """Install a versioned library into a destination by copying,
    (including copying permission/mode bits) and then creating
    required symlinks."""

    if os.path.isdir(source):
        raise SCons.Errors.UserError("cannot install directory `%s' as a version library" % str(source) )
    else:
        # remove the link if it is already there
        try:
            os.remove(dest)
        except:
            pass
        shutil.copy2(source, dest)
        st = os.stat(source)
        os.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
        installShlibLinks(dest, source, env)

    return 0 
Example #4
Source File: main.py    From workload-collocation-agent with Apache License 2.0 6 votes vote down vote up
def valid_config_file(config):
    if not os.path.isabs(config):
        log.error(
            'Error: The config path is not valid. The path must be absolute.')
        exit(1)

    file_owner_uid = os.stat(config).st_uid
    user_uid = os.getuid()
    if user_uid != file_owner_uid and user_uid != 0:
        log.error(
            'Error: The config is not valid. User is not owner of the config or is not root.')
        exit(1)

    mode = stat.S_IMODE(os.stat(config).st_mode)
    other_write_mode = mode & 0b10  # Check if other class write mode flag is set.

    if other_write_mode:
        log.error(
            'Error: The config is not valid. It does not have correct ACLs. '
            'Only owner should be able to write (Hint: try chmod og-rwto fix the problem).'
        )
        exit(1) 
Example #5
Source File: CacheDir.py    From web2board with GNU Lesser General Public License v3.0 6 votes vote down vote up
def CacheRetrieveFunc(target, source, env):
    t = target[0]
    fs = t.fs
    cd = env.get_CacheDir()
    cachedir, cachefile = cd.cachepath(t)
    if not fs.exists(cachefile):
        cd.CacheDebug('CacheRetrieve(%s):  %s not in cache\n', t, cachefile)
        return 1
    cd.CacheDebug('CacheRetrieve(%s):  retrieving from %s\n', t, cachefile)
    if SCons.Action.execute_actions:
        if fs.islink(cachefile):
            fs.symlink(fs.readlink(cachefile), t.get_internal_path())
        else:
            env.copy_from_cache(cachefile, t.get_internal_path())
        st = fs.stat(cachefile)
        fs.chmod(t.get_internal_path(), stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
    return 0 
Example #6
Source File: shutil.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def copymode(src, dst, *, follow_symlinks=True):
    """Copy mode bits from src to dst.

    If follow_symlinks is not set, symlinks aren't followed if and only
    if both `src` and `dst` are symlinks.  If `lchmod` isn't available
    (e.g. Linux) this method does nothing.

    """
    if not follow_symlinks and os.path.islink(src) and os.path.islink(dst):
        if hasattr(os, 'lchmod'):
            stat_func, chmod_func = os.lstat, os.lchmod
        else:
            return
    elif hasattr(os, 'chmod'):
        stat_func, chmod_func = os.stat, os.chmod
    else:
        return

    st = stat_func(src)
    chmod_func(dst, stat.S_IMODE(st.st_mode)) 
Example #7
Source File: install.py    From arnold-usd with Apache License 2.0 6 votes vote down vote up
def copyFunc(dest, source, env):
    """Install a source file or directory into a destination by copying,
    (including copying permission/mode bits)."""

    if os.path.isdir(source):
        if os.path.exists(dest):
            if not os.path.isdir(dest):
                raise SCons.Errors.UserError("cannot overwrite non-directory `%s' with a directory `%s'" % (str(dest), str(source)))
        else:
            parent = os.path.split(dest)[0]
            if not os.path.exists(parent):
                os.makedirs(parent)
        scons_copytree(source, dest)
    else:
        shutil.copy2(source, dest)
        st = os.stat(source)
        os.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)

    return 0

#
# Functions doing the actual work of the InstallVersionedLib Builder.
# 
Example #8
Source File: install.py    From arnold-usd with Apache License 2.0 6 votes vote down vote up
def copyFuncVersionedLib(dest, source, env):
    """Install a versioned library into a destination by copying,
    (including copying permission/mode bits) and then creating
    required symlinks."""

    if os.path.isdir(source):
        raise SCons.Errors.UserError("cannot install directory `%s' as a version library" % str(source) )
    else:
        # remove the link if it is already there
        try:
            os.remove(dest)
        except:
            pass
        shutil.copy2(source, dest)
        st = os.stat(source)
        os.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
        installShlibLinks(dest, source, env)

    return 0 
Example #9
Source File: downloader.py    From polyglot with GNU General Public License v3.0 6 votes vote down vote up
def is_writable(path):
  # Ensure that it exists.
  if not os.path.exists(path):
    return False

  # If we're on a posix system, check its permissions.
  if hasattr(os, 'getuid'):
    statdata = os.stat(path)
    perm = stat.S_IMODE(statdata.st_mode)
    # is it world-writable?
    if (perm & 0o002):
      return True
    # do we own it?
    elif statdata.st_uid == os.getuid() and (perm & 0o200):
      return True
    # are we in a group that can write to it?
    elif (statdata.st_gid in [os.getgid()] + os.getgroups()) and (perm & 0o020):
      return True
    # otherwise, we can't write to it.
    else:
      return False

  # Otherwise, we'll assume it's writable.
  # [xx] should we do other checks on other platforms?
  return True 
Example #10
Source File: shutil.py    From jawfish with MIT License 6 votes vote down vote up
def copymode(src, dst, *, follow_symlinks=True):
    """Copy mode bits from src to dst.

    If follow_symlinks is not set, symlinks aren't followed if and only
    if both `src` and `dst` are symlinks.  If `lchmod` isn't available
    (e.g. Linux) this method does nothing.

    """
    if not follow_symlinks and os.path.islink(src) and os.path.islink(dst):
        if hasattr(os, 'lchmod'):
            stat_func, chmod_func = os.lstat, os.lchmod
        else:
            return
    elif hasattr(os, 'chmod'):
        stat_func, chmod_func = os.stat, os.chmod
    else:
        return

    st = stat_func(src)
    chmod_func(dst, stat.S_IMODE(st.st_mode)) 
Example #11
Source File: test_tempfile.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_mode(self):
        # mkdtemp creates directories with the proper mode
        if not has_stat:
            return            # ugh, can't use SkipTest.

        dir = self.do_create()
        try:
            mode = stat.S_IMODE(os.stat(dir).st_mode)
            mode &= 0777 # Mask off sticky bits inherited from /tmp
            expected = 0700
            if sys.platform in ('win32', 'os2emx'):
                # There's no distinction among 'user', 'group' and 'world';
                # replicate the 'user' bits.
                user = expected >> 6
                expected = user * (1 + 8 + 64)
            self.assertEqual(mode, expected)
        finally:
            os.rmdir(dir) 
Example #12
Source File: test_import.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_execute_bit_not_copied(self):
        # Issue 6070: under posix .pyc files got their execute bit set if
        # the .py file had the execute bit set, but they aren't executable.
        oldmask = os.umask(022)
        sys.path.insert(0, os.curdir)
        try:
            fname = TESTFN + os.extsep + "py"
            f = open(fname, 'w').close()
            os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                             stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
            __import__(TESTFN)
            fn = fname + 'c'
            if not os.path.exists(fn):
                fn = fname + 'o'
                if not os.path.exists(fn):
                    self.fail("__import__ did not result in creation of "
                              "either a .pyc or .pyo file")
            s = os.stat(fn)
            self.assertEqual(stat.S_IMODE(s.st_mode),
                             stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        finally:
            os.umask(oldmask)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0] 
Example #13
Source File: test_dumbdbm.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_dumbdbm_creation_mode(self):
        try:
            old_umask = os.umask(0002)
            f = dumbdbm.open(_fname, 'c', 0637)
            f.close()
        finally:
            os.umask(old_umask)

        expected_mode = 0635
        if os.name != 'posix' or sys.platform == 'cli':
            # Windows and IronPython only support setting the read-only attribute.
            # This shouldn't fail, but doesn't work like Unix either.
            expected_mode = 0666

        import stat
        st = os.stat(_fname + '.dat')
        self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode)
        st = os.stat(_fname + '.dir')
        self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) 
Example #14
Source File: shutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def copystat(src, dst):
    """Copy file metadata

    Copy the permission bits, last access time, last modification time, and
    flags from `src` to `dst`. On Linux, copystat() also copies the "extended
    attributes" where possible. The file contents, owner, and group are
    unaffected. `src` and `dst` are path names given as strings.
    """
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError, why:
            for err in 'EOPNOTSUPP', 'ENOTSUP':
                if hasattr(errno, err) and why.errno == getattr(errno, err):
                    break
            else:
                raise 
Example #15
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copymode_remote_to_local(smb_share, tmpdir):
    test_dir = tmpdir.mkdir("test")
    src_filename = "%s\\source.txt" % smb_share
    dst_filename = "%s\\target.txt" % test_dir

    with open_file(src_filename, mode='w', file_attributes=FileAttributes.FILE_ATTRIBUTE_READONLY) as fd:
        fd.write(u"content")

    with open(dst_filename, mode='w') as fd:
        fd.write(u"content")

    copymode(src_filename, dst_filename)

    actual = os.stat(dst_filename).st_mode
    assert stat.S_IMODE(actual) & stat.S_IWRITE == 0

    remove(src_filename)
    with open_file(src_filename, mode='w') as fd:
        fd.write(u"content")

    copymode(src_filename, dst_filename)

    actual = os.stat(dst_filename).st_mode
    assert stat.S_IMODE(actual) & stat.S_IWRITE == stat.S_IWRITE 
Example #16
Source File: test_import.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_execute_bit_not_copied(self):
        # Issue 6070: under posix .pyc files got their execute bit set if
        # the .py file had the execute bit set, but they aren't executable.
        oldmask = os.umask(022)
        sys.path.insert(0, os.curdir)
        try:
            fname = TESTFN + os.extsep + "py"
            f = open(fname, 'w').close()
            os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                             stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
            __import__(TESTFN)
            fn = fname + 'c'
            if not os.path.exists(fn):
                fn = fname + 'o'
                if not os.path.exists(fn):
                    self.fail("__import__ did not result in creation of "
                              "either a .pyc or .pyo file")
            s = os.stat(fn)
            self.assertEqual(stat.S_IMODE(s.st_mode),
                             stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        finally:
            os.umask(oldmask)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0] 
Example #17
Source File: shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def copymode(src, dst, follow_symlinks=True, **kwargs):
    """
    Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. Due to the
    limitations of Windows, this function only sets/unsets the dst's FILE_ATTRIBUTE_READ_ONLY flag based on what src's
    attribute is set to.

    If follow_symlinks is 'False', and both src and dst are symbolic links, copymode() will attempt to modify the mode
    of dst itself (rather than the file it points to).

    This function supports src and dst being either a local or UNC path. A relative path will be resolved based on the
    current working directory.

    :param src: The src file or directory to copy the read only flag from.
    :param dst: The dst file or directory to copy the read only flag to.
    :param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
    :param kwargs: Common arguments used to build the SMB Session for any UNC paths.
    """
    src_mode = stat.S_IMODE(_get_file_stat(src, follow_symlinks, **kwargs).st_mode)

    norm_dst = ntpath.normpath(dst)
    if norm_dst.startswith('\\\\'):
        read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
        _set_file_basic_info(dst, follow_symlinks, read_only=read_only, **kwargs)
    else:
        _local_chmod(dst, src_mode, follow_symlinks) 
Example #18
Source File: bccache.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        def _unsafe_dir():
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            _unsafe_dir()

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)

        try:
            os.mkdir(actual_dir, stat.S_IRWXU)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        try:
            os.chmod(actual_dir, stat.S_IRWXU)
            actual_dir_stat = os.lstat(actual_dir)
            if actual_dir_stat.st_uid != os.getuid() \
               or not stat.S_ISDIR(actual_dir_stat.st_mode) \
               or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
                _unsafe_dir()
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
           or not stat.S_ISDIR(actual_dir_stat.st_mode) \
           or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            _unsafe_dir()

        return actual_dir 
Example #19
Source File: shutil.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def copystat(src, dst):
    """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError as why:
            if (not hasattr(errno, 'EOPNOTSUPP') or
                why.errno != errno.EOPNOTSUPP):
                raise 
Example #20
Source File: test_tempfile.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_file_mode(self):
        # _mkstemp_inner creates files with the proper mode
        if not has_stat:
            return            # ugh, can't use SkipTest.

        file = self.do_create()
        mode = stat.S_IMODE(os.stat(file.name).st_mode)
        expected = 0600
        if sys.platform in ('win32', 'os2emx'):
            # There's no distinction among 'user', 'group' and 'world';
            # replicate the 'user' bits.
            user = expected >> 6
            expected = user * (1 + 8 + 64)
        self.assertEqual(mode, expected) 
Example #21
Source File: shutil.py    From BinderFilter with MIT License 5 votes vote down vote up
def copymode(src, dst):
    """Copy mode bits from src to dst"""
    if hasattr(os, 'chmod'):
        st = os.stat(src)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst, mode) 
Example #22
Source File: _external_runtime.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _find_executable(prog, pathext=("",)):
    """protected"""
    pathlist = _decode_if_not_text(os.environ.get('PATH', '')).split(os.pathsep)

    for dir in pathlist:
        for ext in pathext:
            filename = os.path.join(dir, prog + ext)
            try:
                st = os.stat(filename)
            except os.error:
                continue
            if stat.S_ISREG(st.st_mode) and (stat.S_IMODE(st.st_mode) & 0o111):
                return filename
    return None 
Example #23
Source File: FS.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _copy_func(fs, src, dest):
    shutil.copy2(src, dest)
    st = fs.stat(src)
    fs.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE) 
Example #24
Source File: plugin.py    From phpsploit with GNU General Public License v3.0 5 votes vote down vote up
def mode_perms(mode):
    octal = oct(stat.S_IMODE(mode))[2:].zfill(4)
    literal = stat.filemode(mode)
    return "%s (%s)" % (octal, literal) 
Example #25
Source File: shutil.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def copystat(src, dst):
    """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError as why:
            if (not hasattr(errno, 'EOPNOTSUPP') or
                why.errno != errno.EOPNOTSUPP):
                raise 
Example #26
Source File: shutil.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def copymode(src, dst):
    """Copy mode bits from src to dst"""
    if hasattr(os, 'chmod'):
        st = os.stat(src)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst, mode) 
Example #27
Source File: shutil.py    From Python24 with MIT License 5 votes vote down vote up
def copystat(src, dst):
    """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError as why:
            if (not hasattr(errno, 'EOPNOTSUPP') or
                why.errno != errno.EOPNOTSUPP):
                raise 
Example #28
Source File: shutil.py    From Python24 with MIT License 5 votes vote down vote up
def copymode(src, dst):
    """Copy mode bits from src to dst"""
    if hasattr(os, 'chmod'):
        st = os.stat(src)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst, mode) 
Example #29
Source File: utils_misc.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def get_writable_features(self):
        """Get writable features for setting"""
        writable_features = []
        if self.interface == "sysfs":
            # Get writable parameters
            for key, value in list(self.ksm_params.items()):
                if stat.S_IMODE(os.stat(value).st_mode) & stat.S_IWRITE:
                    writable_features.append(key)
        else:
            for key in list(self.ksm_params.keys()):
                writable_features.append(key)
        return writable_features 
Example #30
Source File: test_tempfile.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_file_mode(self):
        # _mkstemp_inner creates files with the proper mode

        file = self.do_create()
        mode = stat.S_IMODE(os.stat(file.name).st_mode)
        expected = 0600
        if sys.platform in ('win32', 'os2emx'):
            # There's no distinction among 'user', 'group' and 'world';
            # replicate the 'user' bits.
            user = expected >> 6
            expected = user * (1 + 8 + 64)
        self.assertEqual(mode, expected)