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


Python os.setgid方法代码示例

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


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

示例1: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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: demote

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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 
开发者ID:masmu,项目名称:pulseaudio-dlna,代码行数:23,代码来源:subprocess.py

示例3: _execChild

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:18,代码来源:process.py

示例4: test_mockSetUid

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:22,代码来源:test_process.py

示例5: test_mockPTYSetUid

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:23,代码来源:test_process.py

示例6: shutil_setuid

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

示例7: switch

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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() 
开发者ID:QData,项目名称:deepWordBug,代码行数:20,代码来源:ext_daemon.py

示例8: set_groups

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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

示例9: run_as

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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

示例10: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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

示例11: createDirs

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

示例12: _setgroup

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [as 别名]
def _setgroup(group):
    ''' Normalizes group to a gid and sets the current gid, or does 
    nothing if group is None.
    '''
    if group is None:
        return
        
    # Normalize group to gid
    elif isinstance(group, str):
        gid = grp.getgrnam(group).gr_gid
    # The group is already a gid.
    else:
        gid = group
        
    try:
        os.setgid(gid)
    except OSError:
        self.logger.error('Unable to change group.')
        sys.exit(1) 
开发者ID:Muterra,项目名称:py_daemoniker,代码行数:21,代码来源:_privdrop_unix.py

示例13: change_process_owner

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

示例14: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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

示例15: make_preexec_fn

# 需要导入模块: import os [as 别名]
# 或者: from os import setgid [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


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