本文整理汇总了Python中os.chown方法的典型用法代码示例。如果您正苦于以下问题:Python os.chown方法的具体用法?Python os.chown怎么用?Python os.chown使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.chown方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createVolumeDirs
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def createVolumeDirs(update):
"""
Create directories required by the chute.
"""
extDataDir = update.cache_get('externalDataDir')
extSystemDir = update.cache_get('externalSystemDir')
if update.updateType == 'delete':
pdos.remove(extDataDir, suppressNotFound=True)
pdos.remove(extSystemDir, suppressNotFound=True)
else:
pdosq.makedirs(extDataDir)
pdosq.makedirs(extSystemDir)
try:
os.chown(extDataDir, settings.CONTAINER_UID, -1)
except:
# chown is not permitted in strict confinement.
# TODO: do we need to chmod the data directory, or does it work
# fine regardless?
pass
示例2: chown
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def chown(self, tarinfo, targetpath):
"""Set owner of targetpath according to tarinfo.
"""
if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
# We have to be root to do so.
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
g = tarinfo.gid
try:
u = pwd.getpwnam(tarinfo.uname)[2]
except KeyError:
u = tarinfo.uid
try:
if tarinfo.issym() and hasattr(os, "lchown"):
os.lchown(targetpath, u, g)
else:
if sys.platform != "os2emx":
os.chown(targetpath, u, g)
except EnvironmentError as e:
raise ExtractError("could not change owner")
示例3: fixup_permissions
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def fixup_permissions(self):
""" Fix permissions under the data directory
This means applying the data directory's permissions and ownership to all underlying parts.
If this fails due to insufficient privileges then it just prints a warning and continues on.
"""
stat = os.stat(self.data)
try:
for root, dirs, files in os.walk(self.data):
for name in files:
path = os.path.join(root, name)
os.chmod(path, stat.st_mode & 0o666)
os.chown(path, stat.st_uid, stat.st_gid)
for name in dirs:
path = os.path.join(root, name)
os.chmod(path, stat.st_mode)
os.chown(path, stat.st_uid, stat.st_gid)
except OSError:
print("WARNING: Failed to set permissions under the data directory (not owned by process?) May need to be manually fixed.")
示例4: _set_handler
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def _set_handler(self, log, output, fmt):
# remove previous gunicorn log handler
h = self._get_gunicorn_handler(log)
if h:
log.handlers.remove(h)
if output is not None:
if output == "-":
h = logging.StreamHandler()
else:
util.check_is_writeable(output)
h = logging.FileHandler(output)
# make sure the user can reopen the file
try:
os.chown(h.baseFilename, self.cfg.user, self.cfg.group)
except OSError:
# it's probably OK there, we assume the user has given
# /dev/null as a parameter.
pass
h.setFormatter(fmt)
h._gunicorn = True
log.addHandler(h)
示例5: chown_path
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def chown_path(path, user=None, group=None):
user_unsudoed = get_user_unsudoed()
if not user:
user = user_unsudoed
if not group:
group = user_unsudoed
try:
uid = pwd.getpwnam(user).pw_uid
gid = grp.getgrnam(group).gr_gid
os.chown(path, uid, gid)
except KeyError as e:
from kano.logging import logger
logger.error(
'user {} or group {} do not match with existing'.format(user, group))
ret_val = False
except OSError as e:
from kano.logging import logger
logger.error(
'Error while trying to chown, root priviledges needed {}'.format(e))
ret_val = False
else:
ret_val = True
return ret_val
示例6: run
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def run(self):
result = install_lib.run(self)
fullfname = os.path.join(self.install_dir, 'ivre', '__init__.py')
tmpfname = "%s.tmp" % fullfname
stat = os.stat(fullfname)
os.rename(fullfname, tmpfname)
with open(fullfname, 'w') as newf:
with open(tmpfname) as oldf:
for line in oldf:
if line.startswith('import '):
newf.write('VERSION = %r\n' % VERSION)
break
newf.write(line)
os.chown(fullfname, stat.st_uid, stat.st_gid)
os.chmod(fullfname, stat.st_mode)
os.unlink(tmpfname)
return result
示例7: chown
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def chown(self, tarinfo, targetpath):
"""Set owner of targetpath according to tarinfo.
"""
if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
# We have to be root to do so.
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
g = tarinfo.gid
try:
u = pwd.getpwnam(tarinfo.uname)[2]
except KeyError:
u = tarinfo.uid
try:
if tarinfo.issym() and hasattr(os, "lchown"):
os.lchown(targetpath, u, g)
else:
if sys.platform != "os2emx":
os.chown(targetpath, u, g)
except EnvironmentError, e:
raise ExtractError("could not change owner")
示例8: setup_outputdir
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def setup_outputdir(self, output_dir, uid, gid):
"""
If necessary create or change ownership of the output directory.
"""
if not os.path.exists(output_dir):
try:
os.makedirs(output_dir)
except Exception as ex:
logger.error('Could not created dir %s : %s' %
(output_dir, str(ex)))
return False
try:
os.chown(output_dir, uid, gid)
except Exception as ex:
logger.error('Could not change ownership of %s: %s' %
(output_dir, str(ex)))
return False
return True
示例9: chown
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def chown(self, tarinfo, targetpath, numeric_owner):
"""Set owner of targetpath according to tarinfo. If numeric_owner
is True, use .gid/.uid instead of .gname/.uname.
"""
if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
# We have to be root to do so.
if numeric_owner:
g = tarinfo.gid
u = tarinfo.uid
else:
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
g = tarinfo.gid
try:
u = pwd.getpwnam(tarinfo.uname)[2]
except KeyError:
u = tarinfo.uid
try:
if tarinfo.issym() and hasattr(os, "lchown"):
os.lchown(targetpath, u, g)
else:
os.chown(targetpath, u, g)
except OSError as e:
raise ExtractError("could not change owner")
示例10: sync
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def sync(self):
self._check_writable()
f = self._open(self._tmp_name, "wb", self._mode)
self._pickle_dump(self._dict, f, 1)
f.close()
# Windows doesn't allow renaming if the file exists, so unlink
# it first, chmod'ing it to make sure we can do so. On UNIX, we
# may not be able to chmod the file if it's owned by someone else
# (e.g. from a previous run as root). We should still be able to
# unlink() the file if the directory's writable, though, so ignore
# any OSError exception thrown by the chmod() call.
try: self._os_chmod(self._file_name, 0777)
except OSError: pass
self._os_unlink(self._file_name)
self._os_rename(self._tmp_name, self._file_name)
if self._os_chown is not None and self._chown_to > 0: # don't chown to root or -1
try:
self._os_chown(self._file_name, self._chown_to, self._chgrp_to)
except OSError:
pass
self._needs_sync = 00000
if (keep_all_files):
self._shutil_copyfile(
self._file_name,
self._file_name + "_" + str(int(self._time_time())))
示例11: prepare
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def prepare():
# create control file if necessary
if not os.path.exists(filepath):
f = file(filepath, "w")
f.write("255") # continous lit
f.close()
# fix ownership
os.chown(filepath, pwd.getpwnam(uid).pw_uid, grp.getgrnam(gid).gr_gid)
os.chmod(filepath, 0o666)
# setup manual led control
with open(ledpath + "trigger", "w") as trigger:
trigger.write("none")
# disable LED
with open(ledpath + "brightness", "w") as brightness:
brightness.write("1")
示例12: WriteImageInfo
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def WriteImageInfo(self, mounted_sparsebundle, package_report):
"""Writes information about the image to a plist file in the image."""
imageinfo = ('%s/etc/imageinfo.plist' % mounted_sparsebundle)
cmd = ['defaults', 'write', imageinfo, 'ImageVersion',
'-string', self.image_creation_time]
(unused_stdout, stderr, rc) = RunProcess(cmd)
if rc:
print 'Failed to write ImageVersion: %s' % stderr
cmd = ['defaults', 'write', imageinfo, 'ImageMethod',
'-string', 'can_haz_image']
(unused_stdout, stderr, rc) = RunProcess(cmd)
if rc:
print 'Failed to write ImageMethod: %s' % stderr
for package in package_report:
cmd = ['defaults', 'write', imageinfo, 'ImagePackages',
'-array-add', package]
(unused_stdout, stderr, rc) = RunProcess(cmd)
if rc:
print 'Failed to write ImagePackages: %s' % stderr
# chmod to 0644, chown to root:wheel
os.chmod(imageinfo, 0644)
os.chown(imageinfo, 0, 0)
示例13: chown
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def chown(path, user=None, group=None):
"""Change owner user and group of the given path.
user and group can be the uid/gid or the user/group names, and in that case,
they are converted to their respective uid/gid.
"""
if user is None and group is None:
raise ValueError("user and/or group must be set")
_user = user
_group = group
# -1 means don't change it
if user is None:
_user = -1
# user can either be an int (the uid) or a string (the system username)
elif isinstance(user, str):
_user = _get_uid(user)
if _user is None:
raise LookupError("no such user: {!r}".format(user))
if group is None:
_group = -1
elif not isinstance(group, int):
_group = _get_gid(group)
if _group is None:
raise LookupError("no such group: {!r}".format(group))
os.chown(path, _user, _group)
示例14: extractall
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
"""
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 0o700
# Do not set_attrs directories, as we will do that further down
self.extract(tarinfo, path, set_attrs=not tarinfo.isdir())
# Reverse sort directories.
directories.sort(key=lambda a: a.name)
directories.reverse()
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError as e:
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
示例15: chown
# 需要导入模块: import os [as 别名]
# 或者: from os import chown [as 别名]
def chown(self, user, group, rec=0):
""" change ownership to the given user and group.
user and group may be specified by a number or
by a name. if rec is True change ownership
recursively.
"""
uid = getuserid(user)
gid = getgroupid(group)
if rec:
for x in self.visit(rec=lambda x: x.check(link=0)):
if x.check(link=0):
py.error.checked_call(os.chown, str(x), uid, gid)
py.error.checked_call(os.chown, str(self), uid, gid)