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


Python os.setgroups方法代码示例

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


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

示例1: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [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) 
开发者ID:laurivosandi,项目名称:certidude,代码行数:22,代码来源:common.py

示例2: set_groups

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def set_groups(path, new_uid, new_gid, verbose=True):
    '''For sudo case, set GID to non-SuperUser value.'''
    if not app_state['sudo_based_usage']:
        debug('set_groups: called for non-sudo use')
        return False
    try:
        debug('Changing file owner: file=' + path + ', uid=' + str(new_uid))
        new_gid_list = []
        new_gid_list = os.getgroups()
        if verbose:
            debug('os.getgroups: new_gid_list: ' + str(new_gid_list))
        os.setgroups([])
        if verbose:
            debug('calling os.setgroups(' + str(new_gid_list) + ')..')
        # os.setgroups(new_gid_list)  # XXX macOS: ValueError: too many groups
        os.setgroups([new_gid_list[0]])  # XXX macOS: ValueError: too many groups
        if verbose:
            debug('calling os.setgid(' + str(new_gid) + ')..')
        os.setgid(new_gid)
    except OSError as e:
        critical(e, 'Unable to to update UID on file: ' + path)
        sys.exc_info()
        log('Exception ' + str(e.errno) + ': ' + str(e))
        return False
    return True 
开发者ID:PreOS-Security,项目名称:fwaudit,代码行数:27,代码来源:fwaudit.py

示例3: run_as

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [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 
开发者ID:kdart,项目名称:pycopia,代码行数:24,代码来源:proctools.py

示例4: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [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 
开发者ID:pepsik-kiev,项目名称:HTTPAceProxy,代码行数:25,代码来源:acehttp.py

示例5: setup_uid_manager

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def setup_uid_manager(mockgid):
    unprivUid = os.getuid()
    unprivGid = os.getgid()

    # sudo
    if os.environ.get("SUDO_UID") is not None:
        unprivUid = int(os.environ['SUDO_UID'])
        os.setgroups((mockgid,))
        unprivGid = int(os.environ['SUDO_GID'])

    # consolehelper
    if os.environ.get("USERHELPER_UID") is not None:
        unprivUid = int(os.environ['USERHELPER_UID'])
        unprivName = pwd.getpwuid(unprivUid).pw_name
        secondary_groups = [g.gr_gid for g in grp.getgrall() if unprivName in g.gr_mem]
        os.setgroups([mockgid] + secondary_groups)
        unprivGid = pwd.getpwuid(unprivUid)[3]

    uidManager = mockbuild.uid.UidManager(unprivUid, unprivGid)
    return uidManager 
开发者ID:rpm-software-management,项目名称:mock,代码行数:22,代码来源:mock.py

示例6: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [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 
开发者ID:2ndquadrant-it,项目名称:barman,代码行数:21,代码来源:utils.py

示例7: make_preexec_fn

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def make_preexec_fn(self, cluster):  # pragma: nocover
        # Borrowed and modified from jupyterhub/spawner.py
        pwnam = getpwnam(cluster.username)
        uid = pwnam.pw_uid
        gid = pwnam.pw_gid
        groups = [g.gr_gid for g in grp.getgrall() if cluster.username in g.gr_mem]
        workdir = cluster.state["workdir"]

        def preexec():
            os.setgid(gid)
            try:
                os.setgroups(groups)
            except Exception as e:
                print("Failed to set groups %s" % e, file=sys.stderr)
            os.setuid(uid)
            os.chdir(workdir)

        return preexec 
开发者ID:dask,项目名称:dask-gateway,代码行数:20,代码来源:local.py

示例8: _setgroups_until_success

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def _setgroups_until_success(l):
        while(1):
            # NASTY NASTY HACK (but glibc does it so it must be okay):
            # In case sysconfig didn't give the right answer, find the limit
            # on max groups by just looping, trying to set fewer and fewer
            # groups each time until it succeeds.
            try:
                setgroups(l)
            except ValueError:
                # This exception comes from python itself restricting
                # number of groups allowed.
                if len(l) > 1:
                    del l[-1]
                else:
                    raise
            except OSError, e:
                if e.errno == errno.EINVAL and len(l) > 1:
                    # This comes from the OS saying too many groups
                    del l[-1]
                else:
                    raise
            else:
                # Success, yay!
                return 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:26,代码来源:util.py

示例9: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def drop_privileges(uid_name='nobody'):
    """Drop root privileges."""
    if os.getuid() != 0:
        # We're not root, nothing to do.
        return

    # Get the uid/gid from the name
    (running_uid, _gid) = get_uid_gid(uid_name)

    # Remove group privileges
    os.setgroups([])

    # Try setting the new uid/gid
    os.setuid(running_uid)

    # Ensure a very conservative umask
    os.umask(0o77)

    # TODO: probably redundant, as it will not have access to the
    #                cred cache anyway.
    os.environ['KRB5CCNAME'] = 'FILE:/no_such_krbcc' 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:23,代码来源:utils.py

示例10: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def drop_privileges():

    if os.getuid() != 0:
        return

    if 'SUDO_UID' not in os.environ:
        return

    pwnam = pwd.getpwuid(int(os.environ['SUDO_UID']))

    print('Dropping privileges and going to user', pwnam.pw_name)

    # Remove group privileges
    os.setgroups([])

    # Try setting the new uid/gid
    os.setgid(pwnam.pw_gid)
    os.setuid(pwnam.pw_uid)

    # Ensure a reasonable umask
    os.umask(0o22)

    return True 
开发者ID:fportantier,项目名称:habu,代码行数:25,代码来源:cmd_server_ftp.py

示例11: set_user

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
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) 
开发者ID:ntfreedom,项目名称:neverendshadowsocks,代码行数:32,代码来源:daemon.py

示例12: drop_perms

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def drop_perms() -> None:
    user = getpwnam(os.environ.get('SUDO_USER', 'nobody'))
    uid = user.pw_uid
    gid = user.pw_gid

    os.setgroups([])
    os.setgid(gid)
    os.setuid(uid) 
开发者ID:Yelp,项目名称:synapse-tools,代码行数:10,代码来源:qdisc_tool.py

示例13: _runAsUser

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def _runAsUser(self, f, *args, **kw):
        euid = os.geteuid()
        egid = os.getegid()
        groups = os.getgroups()
        uid, gid = self.getUserGroupId()
        os.setegid(0)
        os.seteuid(0)
        os.setgroups(self.getOtherGroups())
        os.setegid(gid)
        os.seteuid(uid)
        try:
            f = iter(f)
        except TypeError:
            f = [(f, args, kw)]
        try:
            for i in f:
                func = i[0]
                args = len(i) > 1 and i[1] or ()
                kw = len(i) > 2 and i[2] or {}
                r = func(*args, **kw)
        finally:
            os.setegid(0)
            os.seteuid(0)
            os.setgroups(groups)
            os.setegid(egid)
            os.seteuid(euid)
        return r 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:29,代码来源:unix.py

示例14: change_user_group

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def change_user_group(self, user, group):
        if not user and not group:
            return
        import pwd, grp
        uid = gid = None
        if group:
            try:
                gid = int(group)
                group = grp.getgrgid(gid).gr_name
            except ValueError:
                import grp
                try:
                    entry = grp.getgrnam(group)
                except KeyError:
                    raise BadCommand(
                        "Bad group: %r; no such group exists" % group)
                gid = entry.gr_gid
        try:
            uid = int(user)
            user = pwd.getpwuid(uid).pw_name
        except ValueError:
            try:
                entry = pwd.getpwnam(user)
            except KeyError:
                raise BadCommand(
                    "Bad username: %r; no such user exists" % user)
            if not gid:
                gid = entry.pw_gid
            uid = entry.pw_uid
        if self.verbose > 0:
            print('Changing user to %s:%s (%s:%s)' % (
                user, group or '(unknown)', uid, gid))
        if hasattr(os, 'initgroups'):
            os.initgroups(user, gid)
        else:
            os.setgroups([e.gr_gid for e in grp.getgrall()
                          if user in e.gr_mem] + [gid])
        if gid:
            os.setgid(gid)
        if uid:
            os.setuid(uid) 
开发者ID:galaxyproject,项目名称:pulsar,代码行数:43,代码来源:serve.py

示例15: run_as

# 需要导入模块: import os [as 别名]
# 或者: from os import setgroups [as 别名]
def run_as(username, groupname=""):
    """Switch process to run as `username` and optionally `groupname`."""
    pw = pwd.getpwnam(username)
    uid = pw.pw_uid
    gid = grp.getgrnam(groupname).gr_gid if groupname else pw.pw_gid
    os.setgroups([])
    os.setgid(gid)
    os.setuid(uid) 
开发者ID:jaysoffian,项目名称:eap_proxy,代码行数:10,代码来源:eap_proxy.py


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