当前位置: 首页>>代码示例>>Python>>正文


Python shutil.chown方法代码示例

本文整理汇总了Python中shutil.chown方法的典型用法代码示例。如果您正苦于以下问题:Python shutil.chown方法的具体用法?Python shutil.chown怎么用?Python shutil.chown使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在shutil的用法示例。


在下文中一共展示了shutil.chown方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: chown

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def chown(path, user, group=None, recursive=False):
    """ Change user/group ownership of file

    Arguments:
    path: path of file or directory
    user: new owner username
    group: new owner group name
    recursive: set files/dirs recursively
    """
    if group is None:
        group = user

    try:
        if not recursive or os.path.isfile(path):
            shutil.chown(path, user, group)
        else:
            for root, dirs, files in os.walk(path):
                shutil.chown(root, user, group)
                for item in dirs:
                    shutil.chown(os.path.join(root, item), user, group)
                for item in files:
                    shutil.chown(os.path.join(root, item), user, group)
    except OSError as e:
        raise e 
开发者ID:conjure-up,项目名称:conjure-up,代码行数:26,代码来源:utils.py

示例2: __exit__

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def __exit__(self, exc_type, exc_val, traceback):
        if (exc_type is None and self._data_written):
            os.replace(self._temp_file_path, self._config_file)
            os.chmod(self._config_file, 0o660)
            shutil.chown(self._config_file, user=USER, group=GROUP)
        else:
            self._temp_file.close()
            os.unlink(self._temp_file_path)
            if (self._Log):
                self._Log.error(f'configuration manager exiting with error: {exc_val}')

        # releasing lock for purposes specified in flock(1) man page under -u (unlock)
        fcntl.flock(self._config_lock, fcntl.LOCK_UN)
        self._config_lock.close()
        if (self._Log):
            self._Log.debug(f'file lock released for {self._file_name}')

        if (exc_type is not ValidationError):
            return True

    #will load json data from file, convert it to a python dict, then returned as object 
开发者ID:DOWRIGHTTV,项目名称:dnxfirewall-cmd,代码行数:23,代码来源:dnx_file_operations.py

示例3: daemote

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def daemote(pid_file, user, group):
    ''' Change gid and uid, dropping privileges.
    
    Either user or group may explicitly pass None to keep it the same.
    
    The pid_file will be chown'ed so it can still be cleaned up.
    '''
    if not _SUPPORTED_PLATFORM:
        raise OSError('Daemotion is unsupported on your platform.')
    
    # No need to do anything special, just chown the pidfile
    # This will also catch any bad group, user names
    shutil.chown(pid_file, user, group)
    
    # Now update group and then user
    _setgroup(group)
    _setuser(user) 
开发者ID:Muterra,项目名称:py_daemoniker,代码行数:19,代码来源:_privdrop_unix.py

示例4: main

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def main():
  if not options.syslog:
    coloredlogs.install(level=logging.DEBUG if options.debug else logging.INFO,
                        fmt='[%(levelname).1s %(asctime)s %(module)s:%(lineno)d] %(message)s',
                        datefmt='%y%m%d %H:%M:%S')
  else:
    syslog.enable_system_logging(level=logging.DEBUG if options.debug else logging.INFO,
                                 fmt='vj4[%(process)d] %(programname)s %(levelname).1s %(message)s')
  logging.getLogger('aioamqp').setLevel(logging.WARNING)
  logging.getLogger('sockjs').setLevel(logging.WARNING)
  url = urllib.parse.urlparse(options.listen)
  if url.scheme == 'http':
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    host, port_str = url.netloc.rsplit(':', 1)
    sock.bind((host, int(port_str)))
  elif url.scheme == 'unix':
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
      os.remove(url.path)
    except FileNotFoundError:
      pass
    sock.bind(url.path)
    if options.listen_owner or options.listen_group:
      shutil.chown(url.path,
                   user=options.listen_owner if options.listen_owner else None,
                   group=options.listen_group if options.listen_group else None)
    if options.listen_mode:
      os.chmod(url.path, int(options.listen_mode, 8))
  else:
    _logger.error('Invalid listening scheme %s', url.scheme)
    return 1
  for i in range(1, options.prefork):
    pid = os.fork()
    if not pid:
      break
    else:
      atexit.register(lambda: os.kill(pid, signal.SIGTERM))
  web.run_app(app.Application(), sock=sock, access_log=None, shutdown_timeout=0) 
开发者ID:vijos,项目名称:vj4,代码行数:41,代码来源:server.py

示例5: changeOwnerAndGrpToLoggedInUser

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def changeOwnerAndGrpToLoggedInUser(directory, raiseEx=False):
    loggedInUser = getLoggedInUser()
    try:
        shutil.chown(directory, loggedInUser, loggedInUser)
    except Exception as e:
        if raiseEx:
            raise e
        else:
            pass 
开发者ID:hyperledger,项目名称:indy-plenum,代码行数:11,代码来源:sys_util.py

示例6: mkdir

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def mkdir(path):
    if not os.path.isdir(path):
        os.makedirs(path)
        chown(path, install_user(), recursive=True) 
开发者ID:conjure-up,项目名称:conjure-up,代码行数:6,代码来源:utils.py

示例7: spew

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def spew(path, data, owner=None):
    """ Writes data to path
    Arguments:
    path: path of file to write to
    data: contents to write
    owner: optional owner of file
    """
    with open(path, 'w') as f:
        f.write(data)
    if owner:
        try:
            chown(path, owner)
        except:
            raise Exception(
                "Unable to set ownership of {}".format(path)) 
开发者ID:conjure-up,项目名称:conjure-up,代码行数:17,代码来源:utils.py

示例8: change_file_owner

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def change_file_owner(file_path):
    if (os.getuid()):
        raise RuntimeError('process must be ran as root user to change file owner.')

    shutil.chown(file_path, user=USER, group=GROUP)
    os.chmod(file_path, 0o660)

# used to load ip and domain signatures. if whitelist exceptions are specified then they will not
# get loaded into the proxy. the try/except block is used to ensure bad rules dont prevent proxy
# from starting though the bad rule will be ommited from the proxy. 
开发者ID:DOWRIGHTTV,项目名称:dnxfirewall-cmd,代码行数:12,代码来源:dnx_file_operations.py

示例9: test_module_all_attribute

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def test_module_all_attribute(self):
        self.assertTrue(hasattr(shutil, '__all__'))
        target_api = ['copyfileobj', 'copyfile', 'copymode', 'copystat',
                      'copy', 'copy2', 'copytree', 'move', 'rmtree', 'Error',
                      'SpecialFileError', 'ExecError', 'make_archive',
                      'get_archive_formats', 'register_archive_format',
                      'unregister_archive_format', 'get_unpack_formats',
                      'register_unpack_format', 'unregister_unpack_format',
                      'unpack_archive', 'ignore_patterns', 'chown', 'which',
                      'get_terminal_size', 'SameFileError']
        if hasattr(os, 'statvfs') or os.name == 'nt':
            target_api.append('disk_usage')
        self.assertEqual(set(shutil.__all__), set(target_api)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:15,代码来源:test_shutil.py

示例10: change_owner

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def change_owner(full_path, user_name=None, group_name=None):
        try:
            shutil.chown(full_path, user_name, group_name)
        except:
            raise 
开发者ID:Pardus-LiderAhenk,项目名称:ahenk,代码行数:7,代码来源:util.py

示例11: try_set_file_permissions

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def try_set_file_permissions(file):
    """
    Try setting the ownership group and permission of the file

    :param file: full path and filename
    """

    os.chmod(file, 0o660)
    try:
        shutil.chown(file, group='microk8s')
    except:
        # not setting the group means only the current user can access the file
        pass 
开发者ID:ubuntu,项目名称:microk8s,代码行数:15,代码来源:utils.py

示例12: replace_original_passwd

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def replace_original_passwd():
    """
    Move the original passwd bindary file to oldpassword
    Create a symbolic link from /usr/bin/passwd to /usr/share/DefenseMatrix/passwd
    """
    try:
        # Backup original passwd binary
        os.rename('/usr/bin/passwd', '/usr/bin/oldpasswd')
    except FileNotFoundError:
        # We got a problem
        pass
    shutil.copy(os.path.realpath(__file__), '/usr/bin/passwd')
    shutil.chown('/usr/bin/passwd', user=0, group=0)
    os.chmod('/usr/bin/passwd', 0o755) 
开发者ID:k4yt3x,项目名称:defense-matrix,代码行数:16,代码来源:passwd.py

示例13: chown

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def chown(path, user=None, group=None):
    shutil.chown(str(path), user, group)


# Copied from gen/calc.py#L87-L102 
开发者ID:dcos,项目名称:dcos,代码行数:7,代码来源:utils.py

示例14: _set_terraform_binary_permissions

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def _set_terraform_binary_permissions(binary_path):
    """
    Sets the new terraform binary to be executable.
    """
    try:
        os.chmod(binary_path, 0o755)
        try:
            shutil.chown(binary_path, user='apache', group='apache')
        except:
            set_progress(f'Unable to set permissions to apache:apache on {binary_path}. This may cause problems!')
            pass
        return True
    except OSError:
        return False 
开发者ID:CloudBoltSoftware,项目名称:cloudbolt-forge,代码行数:16,代码来源:install_terraform_on_cloudbolt.py

示例15: install_slurm_tmpfile

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import chown [as 别名]
def install_slurm_tmpfile():

    run_dir = Path('/var/run/slurm')

    with open('/etc/tmpfiles.d/slurm.conf', 'w') as f:
        f.write(f"\nd {run_dir} 0755 slurm slurm -")

    if not run_dir.exists():
        run_dir.mkdir(parents=True)
    run_dir.chmod(0o755)

    util.run(f"chown slurm: {run_dir}")

# END install_slurm_tmpfile() 
开发者ID:SchedMD,项目名称:slurm-gcp,代码行数:16,代码来源:setup.py


注:本文中的shutil.chown方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。