我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用stat.S_IMODE。
def check_is_readonly(self, fname): """ Return `True` if @fname is read-only on the filesystem. @fname Path to a file. """ if not fname: return try: mode = os.stat(fname) read_only = (stat.S_IMODE(mode.st_mode) & stat.S_IWUSR != stat.S_IWUSR) except FileNotFoundError: return return read_only
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))
def copytree(src, dst, symlinks = False, ignore = None): if not os.path.exists(dst): os.makedirs(dst) shutil.copystat(src, dst) lst = os.listdir(src) if ignore: excl = ignore(src, lst) lst = [x for x in lst if x not in excl] for item in lst: s = os.path.join(src, item) d = os.path.join(dst, item) if symlinks and os.path.islink(s): if os.path.lexists(d): os.remove(d) os.symlink(os.readlink(s), d) try: st = os.lstat(s) mode = stat.S_IMODE(st.st_mode) os.lchmod(d, mode) except: pass # lchmod not available elif os.path.isdir(s): copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d)
def copystat(cls, src, dest, copy_own=True, copy_xattr=True): """ Copy all stat info (mode bits, atime, mtime, flags) from `src` to `dest`. If `copy_own=True`, the uid and gid are also copied. If `copy_xattr=True`, the extended attributes are also copied (only available on Linux). """ st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dest, mode=mode) os.utime(dest, ns=(st.st_atime_ns, st.st_mtime_ns)) if hasattr(st, "st_flags"): os.chflags(dest, flags=st.st_flags) if copy_own: os.chown(dest, uid=st.st_uid, gid=st.st_gid) if copy_xattr: cls.copyxattr(src, dest)
def startedConnecting(self, connector): fd = connector.transport.fileno() stats = os.fstat(fd) try: filestats = os.stat(connector.transport.addr) except: connector.stopConnecting() return if stat.S_IMODE(filestats[0]) != 0600: log.msg("socket mode is not 0600: %s" % oct(stat.S_IMODE(stats[0]))) elif filestats[4] != os.getuid(): log.msg("socket not owned by us: %s" % stats[4]) elif filestats[5] != os.getgid(): log.msg("socket not owned by our group: %s" % stats[5]) # XXX reenable this when i can fix it for cygwin #elif filestats[-3:] != stats[-3:]: # log.msg("socket doesn't have same create times") else: log.msg('conecting OK') return connector.stopConnecting()
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
def enforce_file_permissions(path): # source: dcos-cli """Enforce 400 or 600 permissions on file :param path: Path to the TOML file :type path: str :rtype: None """ if not os.path.isfile(path): raise Exception('Path [{}] is not a file'.format(path)) permissions = oct(stat.S_IMODE(os.stat(path).st_mode)) if permissions not in ['0o600', '0600', '0o400', '0400']: if os.path.realpath(path) != path: path = '%s (pointed to by %s)' % (os.path.realpath(path), path) msg = ( "Permissions '{}' for configuration file '{}' are too open. " "File must only be accessible by owner. " "Aborting...".format(permissions, path)) raise Exception(msg)
def test_access_token_credentials(self): access_token = 'foo' user_agent = 'refresh_checker/1.0' credentials = client.AccessTokenCredentials(access_token, user_agent) storage = file_module.Storage(FILENAME) credentials = storage.put(credentials) credentials = storage.get() self.assertIsNotNone(credentials) self.assertEquals('foo', credentials.access_token) self.assertTrue(os.path.exists(FILENAME)) if os.name == 'posix': # pragma: NO COVER mode = os.stat(FILENAME).st_mode self.assertEquals('0o600', oct(stat.S_IMODE(mode)))
def copyfile(src, dst): try: f1 = open(src, "rb") if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) f2 = open(dst, "w+b") while True: buf = f1.read(16*1024) if not buf: break f2.write(buf) st = os.stat(src) mode = S_IMODE(st.st_mode) os.chmod(dst, mode) os.utime(dst, (st.st_atime, st.st_mtime)) except: print "copy", src, "to", dst, "failed!" return -1 return 0
def _symbolic_mode_to_octal(self, path_stat, symbolic_mode): new_mode = stat.S_IMODE(path_stat.st_mode) mode_re = re.compile(r'^(?P<users>[ugoa]+)(?P<operator>[-+=])(?P<perms>[rwxXst-]*|[ugo])$') for mode in symbolic_mode.split(','): match = mode_re.match(mode) if match: users = match.group('users') operator = match.group('operator') perms = match.group('perms') if users == 'a': users = 'ugo' for user in users: mode_to_apply = self._get_octal_mode_from_symbolic_perms(path_stat, user, perms) new_mode = self._apply_operation_to_mode(user, operator, mode_to_apply, new_mode) else: raise ValueError("bad symbolic permission for mode: %s" % mode) return new_mode
def test_dumbdbm_creation_mode(self): # On platforms without chmod, don't do anything. if not (hasattr(os, 'chmod') and hasattr(os, 'umask')): return try: old_umask = os.umask(0o002) f = dumbdbm.open(_fname, 'c', 0o637) f.close() finally: os.umask(old_umask) expected_mode = 0o635 if os.name != 'posix': # Windows only supports setting the read-only attribute. # This shouldn't fail, but doesn't work like Unix either. expected_mode = 0o666 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)
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. with temp_umask(0o022): sys.path.insert(0, os.curdir) try: fname = TESTFN + os.extsep + "py" 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)) fn = imp.cache_from_source(fname) unlink(fn) __import__(TESTFN) 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: del sys.path[0] remove_files(TESTFN) unload(TESTFN)
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 &= 0o777 # Mask off sticky bits inherited from /tmp expected = 0o700 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)
def test_perform_permissions(self): self.auth.prepare() # Remove exec bit from permission check, so that it # matches the file self.auth.perform([self.achall]) path_permissions = stat.S_IMODE(os.stat(self.validation_path).st_mode) self.assertEqual(path_permissions, 0o644) # Check permissions of the directories for dirpath, dirnames, _ in os.walk(self.path): for directory in dirnames: full_path = os.path.join(dirpath, directory) dir_permissions = stat.S_IMODE(os.stat(full_path).st_mode) self.assertEqual(dir_permissions, 0o755) parent_gid = os.stat(self.path).st_gid parent_uid = os.stat(self.path).st_uid self.assertEqual(os.stat(self.validation_path).st_gid, parent_gid) self.assertEqual(os.stat(self.validation_path).st_uid, parent_uid)
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]
def test_mode(self): # mkdtemp creates directories with the proper mode 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)
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)
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
def make_writeable(self, filename): """ Make sure that the file is writeable. Useful if our source is read-only. """ if sys.platform.startswith('java'): # On Jython there is no os.access() return if not os.access(filename, os.W_OK): st = os.stat(filename) new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR os.chmod(filename, new_permissions)
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: if (not hasattr(errno, 'EOPNOTSUPP') or why.errno != errno.EOPNOTSUPP): raise
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