本文整理汇总了Python中os.setuid方法的典型用法代码示例。如果您正苦于以下问题:Python os.setuid方法的具体用法?Python os.setuid怎么用?Python os.setuid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.setuid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: drop_privileges
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [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: demote
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def demote(self, uid, gid):
def fn_uid_gid():
os.setgid(gid)
os.setuid(uid)
def fn_uid():
os.setuid(uid)
def fn_gid():
os.setgid(gid)
def fn_nop():
pass
if uid and gid:
return fn_uid_gid
elif uid:
return fn_uid
elif gid:
return fn_gid
return fn_nop
示例3: _execChild
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def _execChild(self, path, uid, gid, executable, args, environment):
"""
The exec() which is done in the forked child.
"""
if path:
os.chdir(path)
if uid is not None or gid is not None:
if uid is None:
uid = os.geteuid()
if gid is None:
gid = os.getegid()
# set the UID before I actually exec the process
os.setuid(0)
os.setgid(0)
switchUID(uid, gid)
os.execvpe(executable, args, environment)
示例4: test_mockSetUid
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def test_mockSetUid(self):
"""
Try creating a process with setting its uid: it's almost the same path
as the standard path, but with a C{switchUID} call before the exec.
"""
cmd = b'/mock/ouch'
d = defer.Deferred()
p = TrivialProcessProtocol(d)
try:
reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
usePTY=False, uid=8080)
except SystemError:
self.assertTrue(self.mockos.exited)
self.assertEqual(
self.mockos.actions,
[('fork', False), ('setuid', 0), ('setgid', 0),
('switchuid', 8080, 1234), 'exec', ('exit', 1)])
else:
self.fail("Should not be here")
示例5: shutil_setuid
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def shutil_setuid(user = None, group = None):
""" set fork-child uid/gid (returns pw-info env-settings)"""
if group:
import grp
gid = grp.getgrnam(group).gr_gid
os.setgid(gid)
logg.debug("setgid %s '%s'", gid, group)
if user:
import pwd
pw = pwd.getpwnam(user)
if not group:
gid = pw.pw_gid
os.setgid(gid)
logg.debug("setgid %s", gid)
uid = pw.pw_uid
os.setuid(uid)
logg.debug("setuid %s '%s'", uid, user)
home = pw.pw_dir
shell = pw.pw_shell
logname = pw.pw_name
return { "USER": user, "LOGNAME": logname, "HOME": home, "SHELL": shell }
return {}
示例6: switch
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def switch(self):
"""
Switch the current process's user/group to ``self.user``, and
``self.group``. Change directory to ``self.dir``, and write the
current pid out to ``self.pid_file``.
"""
# set the running uid/gid
LOG.debug('setting process uid(%s) and gid(%s)' %
(self.user.pw_uid, self.group.gr_gid))
os.setgid(self.group.gr_gid)
os.setuid(self.user.pw_uid)
os.environ['HOME'] = self.user.pw_dir
os.chdir(self.dir)
if self.pid_file and os.path.exists(self.pid_file):
raise exc.FrameworkError("Process already running (%s)" %
self.pid_file)
else:
self._write_pid_file()
示例7: run_as
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def run_as(pwent, umask=0o22):
"""Drop privileges to given user's password entry, and set up
environment. Assumes the parent process has root privileges.
"""
os.umask(umask)
home = pwent.home
try:
os.chdir(home)
except OSError:
os.chdir("/")
# drop privs to user
os.setgroups(pwent.groups)
os.setgid(pwent.gid)
os.setegid(pwent.gid)
os.setuid(pwent.uid)
os.seteuid(pwent.uid)
os.environ["HOME"] = home
os.environ["USER"] = pwent.name
os.environ["LOGNAME"] = pwent.name
os.environ["SHELL"] = pwent.shell
os.environ["PATH"] = "/bin:/usr/bin:/usr/local/bin"
return None
示例8: drop_privileges
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
try: import pwd, grp
except ImportError: return False # Windows
# Get the uid/gid from the name
running_uid = pwd.getpwnam(uid_name).pw_uid
running_uid_home = pwd.getpwnam(uid_name).pw_dir
running_gid = grp.getgrnam(gid_name).gr_gid
# Remove group privileges
os.setgroups([])
# Try setting the new uid/gid
os.setgid(running_gid)
os.setuid(running_uid)
# Ensure a very conservative umask
old_umask = os.umask(int('077', 8))
value = (os.getuid() == running_uid and os.getgid() == running_gid)
if value: # could be useful
os.environ['HOME'] = running_uid_home
logger.info('Changed permissions to: %s: %i, %s, %i' % (uid_name, running_uid, gid_name, running_gid))
return value
示例9: test_mockPTYSetUid
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def test_mockPTYSetUid(self):
"""
Try creating a PTY process with setting its uid: it's almost the same
path as the standard path, but with a C{switchUID} call before the
exec.
"""
cmd = b'/mock/ouch'
d = defer.Deferred()
p = TrivialProcessProtocol(d)
try:
reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
usePTY=True, uid=8081)
except SystemError:
self.assertTrue(self.mockos.exited)
self.assertEqual(
self.mockos.actions,
[('fork', False), 'setsid', ('setuid', 0), ('setgid', 0),
('switchuid', 8081, 1234), 'exec', ('exit', 1)])
else:
self.fail("Should not be here")
示例10: createDirs
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def createDirs(self):
uid_change = pwd.getpwnam(self.user).pw_uid
gid_change = pwd.getpwnam(self.user).pw_gid
pidx = os.fork()
if pidx == 0:
try:
os.setgid(gid_change)
os.setuid(uid_change)
if not os.path.exists(self.directory):
os.makedirs(self.directory)
os.chdir(self.directory)
man_dir = os.path.abspath("manifests")
userlists_dir = os.path.abspath("userlists")
self.copy(self.manifests, man_dir)
self.copy(self.userlists, userlists_dir)
finally:
os._exit(0)
os.waitpid(pidx, 0)
示例11: _setuser
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def _setuser(user):
''' Normalizes user to a uid and sets the current uid, or does
nothing if user is None.
'''
if user is None:
return
# Normalize group to gid
elif isinstance(user, str):
uid = pwd.getpwnam(user).pw_uid
# The group is already a gid.
else:
uid = user
try:
os.setuid(uid)
except OSError:
self.logger.error('Unable to change user.')
sys.exit(1)
示例12: change_process_owner
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def change_process_owner(uid, gid):
""" Change the owning UID and GID of this process.
Sets the GID then the UID of the process (in that order, to
avoid permission errors) to the specified `gid` and `uid`
values. Requires appropriate OS privileges for this process.
"""
try:
os.setgid(gid)
os.setuid(uid)
except Exception, exc:
error = DaemonOSEnvironmentError(
"Unable to change file creation mask (%(exc)s)"
% vars())
raise error
示例13: drop_privileges
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def drop_privileges(user):
"""
Change the system user of the current python process.
It will only work if called as root or as the target user.
:param string user: target user
:raise KeyError: if the target user doesn't exists
:raise OSError: when the user change fails
"""
pw = pwd.getpwnam(user)
if pw.pw_uid == os.getuid():
return
groups = [e.gr_gid for e in grp.getgrall() if pw.pw_name in e.gr_mem]
groups.append(pw.pw_gid)
os.setgroups(groups)
os.setgid(pw.pw_gid)
os.setuid(pw.pw_uid)
os.environ['HOME'] = pw.pw_dir
示例14: GetSensors
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def GetSensors(self, user, scpuser, scppasswd, source, dest):
pw = pwd.getpwnam(user)
uid = pw.pw_uid
os.setuid(uid)
print ("setuid successful to", uid)
try:
scptransfer(scpuser+'@'+source,dest,scppasswd)
except:
print ("Could not connect to/get sensor info of client %s" % clientname)
# TODO
示例15: drop_privileges
# 需要导入模块: import os [as 别名]
# 或者: from os import setuid [as 别名]
def drop_privileges(self, user):
nobody = pwd.getpwnam(user)
try:
os.setgid(nobody.pw_uid)
os.setuid(nobody.pw_gid)
except OSError:
print("Failed to drop privileges. You'll have to start this program as root to be able to do this.")
raise
print("Privileges dropped. Server now running as", user)
print(" uid/gid", os.getuid(), os.getgid())
print(" euid/egid", os.geteuid(), os.getegid())