本文整理汇总了Python中pwd.getpwnam方法的典型用法代码示例。如果您正苦于以下问题:Python pwd.getpwnam方法的具体用法?Python pwd.getpwnam怎么用?Python pwd.getpwnam使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pwd
的用法示例。
在下文中一共展示了pwd.getpwnam方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: drop_privileges
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def drop_privileges():
from certidude import config
import pwd
_, _, uid, gid, gecos, root, shell = pwd.getpwnam("certidude")
restricted_groups = []
restricted_groups.append(gid)
# PAM needs access to /etc/shadow
if config.AUTHENTICATION_BACKENDS == {"pam"}:
import grp
name, passwd, num, mem = grp.getgrnam("shadow")
click.echo("Adding current user to shadow group due to PAM authentication backend")
restricted_groups.append(num)
os.setgroups(restricted_groups)
os.setgid(gid)
os.setuid(uid)
click.echo("Switched %s (pid=%d) to user %s (uid=%d, gid=%d); member of groups %s" %
(getproctitle(), os.getpid(), "certidude", os.getuid(), os.getgid(), ", ".join([str(j) for j in os.getgroups()])))
os.umask(0o007)
示例2: chown
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [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: setUpClass
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def setUpClass(cls):
# Tests are depending on two existing and distinct users and groups.
# We chose 'root' with uid/gid 0 and 'nobody', because both exist on
# all relevant platforms. Tests use a mocked request so they run
# under any user.
cls.user = user = pwd.getpwnam('nobody')
cls.group = group = grp.getgrgid(user.pw_gid)
cls.parser = configparser.ConfigParser(
interpolation=configparser.ExtendedInterpolation(),
defaults={
'other_uid': str(user.pw_uid),
'other_username': user.pw_name,
'other_gid': str(group.gr_gid),
'other_groupname': group.gr_name,
}
)
cls.parser.read_string(CONFIG)
示例4: add_user
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def add_user(self, user):
'''Import a user into /etc/passwd on the image. You can specify a
username, in which case add_user will look up the password entry
via getpwnam(), or you can provide a colon-delimited password
entry, which will be used verbatim.'''
LOG.info('adding user %s', user)
if ':' in user:
self.users.append(user)
else:
pwent = pwd.getpwnam(user)
self.users.append(':'.join(str(x) for x in pwent))
grent = grp.getgrgid(pwent.pw_gid)
self.groups.append(':'.join(str(x) for x in
grent[:3] + (','.join(grent[3]),)
if not isinstance(x, list)))
示例5: create_instance_user
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def create_instance_user(problem_name, instance_number):
"""
Generates a random username based on the problem name. The username returned is guaranteed to
not exist.
Args:
problem_name: The name of the problem
instance_number: The unique number for this instance
Returns:
The created username
"""
converted_name = sanitize_name(problem_name)
username = get_username(converted_name, instance_number)
try:
# Check if the user already exists.
user = getpwnam(username)
new = False
except KeyError:
create_user(username)
new = True
return username, new
示例6: chown_path
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [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
示例7: chown
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [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: chown
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [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")
示例9: prepare
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [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")
示例10: uid
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def uid(self, val):
if val is not None:
if pwd is None:
self.bus.log('pwd module not available; ignoring uid.',
level=30)
val = None
elif isinstance(val, text_or_bytes):
val = pwd.getpwnam(val)[2]
self._uid = val
示例11: get
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def get(self, username):
_, _, _, _, gecos, _, _ = pwd.getpwnam(username)
gecos = gecos.split(",")
full_name = gecos[0]
mail = "%s@%s" % (username, config.MAIL_SUFFIX)
if full_name and " " in full_name:
given_name, surname = full_name.split(" ", 1)
return User(username, mail, given_name, surname)
return User(username, mail)
示例12: _get_uid
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def _get_uid(name):
"""Returns an uid, given a user name."""
if getpwnam is None or name is None:
return None
try:
result = getpwnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None
示例13: expanduser
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def expanduser(path):
"""Expand ~ and ~user constructions. If user or $HOME is unknown,
do nothing."""
if isinstance(path, bytes):
tilde = b'~'
else:
tilde = '~'
if not path.startswith(tilde):
return path
sep = _get_sep(path)
i = path.find(sep, 1)
if i < 0:
i = len(path)
if i == 1:
if 'HOME' not in os.environ:
import pwd
userhome = pwd.getpwuid(os.getuid()).pw_dir
else:
userhome = os.environ['HOME']
else:
import pwd
name = path[1:i]
if isinstance(name, bytes):
name = str(name, 'ASCII')
try:
pwent = pwd.getpwnam(name)
except KeyError:
return path
userhome = pwent.pw_dir
if isinstance(path, bytes):
userhome = os.fsencode(userhome)
root = b'/'
else:
root = '/'
userhome = userhome.rstrip(root)
return (userhome + path[i:]) or root
# Expand paths containing shell variable substitutions.
# This expands the forms $variable and ${variable} only.
# Non-existent variables are left unchanged.
示例14: nobody_uid
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def nobody_uid():
"""Internal routine to get nobody's uid"""
global nobody
if nobody:
return nobody
try:
import pwd
except ImportError:
return -1
try:
nobody = pwd.getpwnam('nobody')[2]
except KeyError:
nobody = 1 + max(x[2] for x in pwd.getpwall())
return nobody
示例15: _get_pwd_uid
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwnam [as 别名]
def _get_pwd_uid(self, section, name, default):
value = self.parser.get(section, name, fallback=default)
try:
return int(value)
except ValueError:
return pwd.getpwnam(value).pw_uid