def set_user(username):
if username is None:
return
import pwd
import grp
try:
pwrec = pwd.getpwnam(username)
except KeyError:
logging.error('user not found: %s' % username)
raise
user = pwrec[0]
uid = pwrec[2]
gid = pwrec[3]
cur_uid = os.getuid()
if uid == cur_uid:
return
if cur_uid != 0:
logging.error('can not set user as nonroot user')
# will raise later
# inspired by supervisor
if hasattr(os, 'setgroups'):
groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
groups.insert(0, gid)
os.setgroups(groups)
os.setgid(gid)
os.setuid(uid)
python类getgrall()的实例源码
def setUp(self):
if POSIX:
import pwd
import grp
users = pwd.getpwall()
groups = grp.getgrall()
self.all_uids = set([x.pw_uid for x in users])
self.all_usernames = set([x.pw_name for x in users])
self.all_gids = set([x.gr_gid for x in groups])
def set_user(username):
if username is None:
return
import pwd
import grp
try:
pwrec = pwd.getpwnam(username)
except KeyError:
logging.error('user not found: %s' % username)
raise
user = pwrec[0]
uid = pwrec[2]
gid = pwrec[3]
cur_uid = os.getuid()
if uid == cur_uid:
return
if cur_uid != 0:
logging.error('can not set user as nonroot user')
# will raise later
# inspired by supervisor
if hasattr(os, 'setgroups'):
groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
groups.insert(0, gid)
os.setgroups(groups)
os.setgid(gid)
os.setuid(uid)
def setUp(self):
if POSIX:
import pwd
import grp
users = pwd.getpwall()
groups = grp.getgrall()
self.all_uids = set([x.pw_uid for x in users])
self.all_usernames = set([x.pw_name for x in users])
self.all_gids = set([x.gr_gid for x in groups])
def set_user(username):
if username is None:
return
import pwd
import grp
try:
pwrec = pwd.getpwnam(username)
except KeyError:
logging.error('user not found: %s' % username)
raise
user = pwrec[0]
uid = pwrec[2]
gid = pwrec[3]
cur_uid = os.getuid()
if uid == cur_uid:
return
if cur_uid != 0:
logging.error('can not set user as nonroot user')
# will raise later
# inspired by supervisor
if hasattr(os, 'setgroups'):
groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
groups.insert(0, gid)
os.setgroups(groups)
os.setgid(gid)
os.setuid(uid)
def check(bot, msg):
"""Print information about an OCF user."""
user = msg.match.group(1).strip()
attrs = search.user_attrs(user)
if attrs is not None:
groups = [grp.getgrgid(attrs['gidNumber']).gr_name]
groups.extend(sorted(
group.gr_name for group in grp.getgrall() if user in group.gr_mem
))
groups = [
'{}{}\x0f'.format(GROUP_COLOR_MAPPING.get(group, ''), group)
for group in groups
]
if 'creationTime' in attrs:
created = attrs['creationTime'].strftime('%Y-%m-%d')
else:
created = 'unknown'
msg.respond(
'{user} ({uid}) | {name} | created {created} | groups: {groups}'.format(
user=user,
uid=attrs['uidNumber'],
name=attrs['cn'][0],
created=created,
groups=', '.join(groups),
),
ping=False,
)
else:
msg.respond('{} does not exist'.format(user), ping=False)
def _get_user_groups(user_name):
"""
Get a list of groups for the user ``user_name``.
"""
groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]
gid = pwd.getpwnam(user_name).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
return groups
def set_user(username):
if username is None:
return
import pwd
import grp
try:
pwrec = pwd.getpwnam(username)
except KeyError:
logging.error('user not found: %s' % username)
raise
user = pwrec[0]
uid = pwrec[2]
gid = pwrec[3]
cur_uid = os.getuid()
if uid == cur_uid:
return
if cur_uid != 0:
logging.error('can not set user as nonroot user')
# will raise later
# inspired by supervisor
if hasattr(os, 'setgroups'):
groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
groups.insert(0, gid)
os.setgroups(groups)
os.setgid(gid)
os.setuid(uid)
def set_user(username):
if username is None:
return
import pwd
import grp
try:
pwrec = pwd.getpwnam(username)
except KeyError:
logging.error('user not found: %s' % username)
raise
user = pwrec[0]
uid = pwrec[2]
gid = pwrec[3]
cur_uid = os.getuid()
if uid == cur_uid:
return
if cur_uid != 0:
logging.error('can not set user as nonroot user')
# will raise later
# inspired by supervisor
if hasattr(os, 'setgroups'):
groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
groups.insert(0, gid)
os.setgroups(groups)
os.setgid(gid)
os.setuid(uid)
def getgrouplist(name, gid):
return [grp.getgrnam(gr.gr_name).gr_gid for gr in grp.getgrall() if name in gr.gr_mem]
def set_user(username):
if username is None:
return
import pwd
import grp
try:
pwrec = pwd.getpwnam(username)
except KeyError:
logging.error('user not found: %s' % username)
raise
user = pwrec[0]
uid = pwrec[2]
gid = pwrec[3]
cur_uid = os.getuid()
if uid == cur_uid:
return
if cur_uid != 0:
logging.error('can not set user as nonroot user')
# will raise later
# inspired by supervisor
if hasattr(os, 'setgroups'):
groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
groups.insert(0, gid)
os.setgroups(groups)
os.setgid(gid)
os.setuid(uid)
def get_group_list(user=None, include_default=True):
'''
Returns a list of all of the system group names of which the user
is a member.
'''
if HAS_GRP is False or HAS_PWD is False:
# We don't work on platforms that don't have grp and pwd
# Just return an empty list
return []
group_names = None
ugroups = set()
if not isinstance(user, six.string_types):
raise Exception
if hasattr(os, 'getgrouplist'):
# Try os.getgrouplist, available in python >= 3.3
log.trace('Trying os.getgrouplist for \'{0}\''.format(user))
try:
group_names = [
grp.getgrgid(grpid).gr_name for grpid in
os.getgrouplist(user, pwd.getpwnam(user).pw_gid)
]
except Exception:
pass
else:
# Try pysss.getgrouplist
log.trace('Trying pysss.getgrouplist for \'{0}\''.format(user))
try:
import pysss # pylint: disable=import-error
group_names = list(pysss.getgrouplist(user))
except Exception:
pass
if group_names is None:
# Fall back to generic code
# Include the user's default group to behave like
# os.getgrouplist() and pysss.getgrouplist() do
log.trace('Trying generic group list for \'{0}\''.format(user))
group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]
try:
default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name
if default_group not in group_names:
group_names.append(default_group)
except KeyError:
# If for some reason the user does not have a default group
pass
ugroups.update(group_names)
if include_default is False:
# Historically, saltstack code for getting group lists did not
# include the default group. Some things may only want
# supplemental groups, so include_default=False omits the users
# default group.
try:
default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name
ugroups.remove(default_group)
except KeyError:
# If for some reason the user does not have a default group
pass
log.trace('Group list for user \'{0}\': \'{1}\''.format(user, sorted(ugroups)))
return sorted(ugroups)
def switchuser(username):
"""
Switch user the process is running as.
This method will only work if is are running as root.
Arguments:
``username'' is the username of the user we want to run as.
Returns/raises:
If switch is a success, returns True.
If user is unknown and we're still running as root, raises
UserNotFoundError.
If failing to switch, raises SwitchUserError.
"""
# Get UID/GID we're running as
olduid = os.getuid()
oldgid = os.getgid()
try:
# Try to get information about the given username
_name, _passwd, uid, gid, _gecos, _dir, _shell = pwd.getpwnam(username)
except KeyError:
raise UserNotFoundError(username)
else:
if olduid != uid:
try:
# Set primary group
os.setgid(gid)
# Set non-primary groups
gids = []
for (_name, _passwd, gid, members) in grp.getgrall():
if username in members:
gids.append(gid)
if len(gids) > 0:
os.setgroups(gids)
# Set user id
os.setuid(uid)
except OSError:
# Failed changing uid/gid
_logger.debug("Failed chaning uid/gid from %d/%d to %d/%d.",
olduid, oldgid, uid, gid)
raise SwitchUserError(olduid, oldgid, uid, gid)
else:
# Switch successful
_logger.debug("uid/gid changed from %d/%d to %d/%d.",
olduid, oldgid, uid, gid)
return True
else:
# Already running as the given user
_logger.debug("Running as uid/gid %d/%d.", olduid, oldgid)
return True