• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python util.switchUID函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twisted.python.util.switchUID函数的典型用法代码示例。如果您正苦于以下问题:Python switchUID函数的具体用法?Python switchUID怎么用?Python switchUID使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: _execChild

 def _execChild(self, path, settingUID, uid, gid, command, args, environment):
     if path:
         os.chdir(path)
     # set the UID before I actually exec the process
     if settingUID:
         switchUID(uid, gid)
     os.execvpe(command, args, environment)
开发者ID:RichDijk,项目名称:eXe,代码行数:7,代码来源:process.py


示例2: cbLoggedIn

        def cbLoggedIn(e, config):
            mail = only(e, config.getLDAPAttributeMailbox())
            username = mail.split('@', 1)[0]
            hostname = mail.split('@', 1)[1]

            username = quot(username)
            hostname = quot(hostname)

            userpad = (username+'__')[:2]

            mailhost = only(e, config.getLDAPAttributeMailHost())

            userdir = os.path.join(
                config.getSpool(),
                hostname,
                mailhost,
                userpad)

            switchUID(uid=pwd.getpwnam('scalemail')[2],
                      gid=grp.getgrnam('scalemail')[2])

            if not os.path.isdir(userdir):
                os.mkdir(userdir, 0700)
            os.chdir(userdir)

            if not os.path.isdir(username):
                initializeMaildir(username)
            os.chdir(username)

            os.execlp(sys.argv[1], *sys.argv[1:])
            print >>sys.stderr, "scalemail-courier-login: Cannot exec command."
            sys.exit(2)
开发者ID:tv42,项目名称:scalemail,代码行数:32,代码来源:checkpassword.py


示例3: test_uid

 def test_uid(self):
     """
     L{util.switchUID} calls L{util.initgroups} and then C{os.setuid} with
     the given uid.
     """
     util.switchUID(12000, None)
     self.assertEqual(self.initgroupsCalls, [(12000, None)])
     self.assertEqual(self.mockos.actions, [("setuid", 12000)])
开发者ID:RedMoons,项目名称:Study_Python_Beautifulsoup4,代码行数:8,代码来源:test_util.py


示例4: test_euid

 def test_euid(self):
     """
     L{util.switchUID} calls L{util.initgroups} and then C{os.seteuid} with
     the given uid if the C{euid} parameter is set to C{True}.
     """
     util.switchUID(12000, None, True)
     self.assertEqual(self.initgroupsCalls, [(12000, None)])
     self.assertEqual(self.mockos.seteuidCalls, [12000])
开发者ID:RedMoons,项目名称:Study_Python_Beautifulsoup4,代码行数:8,代码来源:test_util.py


示例5: main

def main():

    usage = "%prog [options] ACTION"
    epilog = """
ACTION is one of add|modify|remove|print

  add:    add a user record
  modify: modify a user record
  remove: remove a user record
"""
    description = "Tool to manipulate CalendarServer augments XML file"
    version = "%prog v1.0"
    parser = OptionParser(usage=usage, description=description, version=version)
    parser.epilog = epilog
    parser.format_epilog = lambda _:epilog

    parser.add_option("-f", "--file", dest="configfilename",
                      help="caldavd.plist defining Augment Service", metavar="FILE")
    parser.add_option("-u", "--uid", dest="uid",
                      help="OD GUID to manipulate", metavar="UID")
    parser.add_option("-i", "--uidfile", dest="uidfile",
                      help="File containing a list of GUIDs to manipulate", metavar="UIDFILE")
    parser.add_option("-n", "--node", dest="node",
                      help="Partition node to assign to UID", metavar="NODE")
    parser.add_option("-c", "--enable-calendar", action="store_true", dest="enable_calendar",
                      default=True, help="Enable calendaring for this UID: %default")
    parser.add_option("-a", "--enable-addressbooks", action="store_true", dest="enable_addressbook",
                      default=True, help="Enable calendaring for this UID: %default")
    parser.add_option("-s", "--auto-schedule", action="store_true", dest="auto_schedule",
                      default=False, help="Enable auto-schedule for this UID: %default")

    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("incorrect number of arguments")

    observer = StandardIOObserver()
    observer.start()

    #
    # Get configuration
    #
    try:
        loadConfig(options.configfilename)
        setLogLevelForNamespace(None, "warn")

        # Shed privileges
        if config.UserName and config.GroupName and os.getuid() == 0:
            uid = getpwnam(config.UserName).pw_uid
            gid = getgrnam(config.GroupName).gr_gid
            switchUID(uid, uid, gid)

        os.umask(config.umask)

        config.directory = getDirectory()
        autoDisableMemcached(config)
    except ConfigurationError, e:
        usage("Unable to start: %s" % (e,))
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:58,代码来源:manageaugments.py


示例6: switchUID

def switchUID(uid, gid):
    """
    Switch uid and gid to what the user has specified on the command
    line.
    """
    if uid:
        uid = util.uidFromString(uid)
    if gid:
        gid = util.gidFromString(gid)
    util.switchUID(uid, gid)
开发者ID:jrydberg,项目名称:edgy,代码行数:10,代码来源:app.py


示例7: _execChild

 def _execChild(self, path, settingUID, uid, gid, executable, args, environment):
     """
     The exec() which is done in the forked child.
     """
     if path:
         os.chdir(path)
     # set the UID before I actually exec the process
     if settingUID:
         switchUID(uid, gid)
     os.execvpe(executable, args, environment)
开发者ID:Code-Alliance-Archive,项目名称:oh-mainline,代码行数:10,代码来源:process.py


示例8: run

def run():
    import traceback
    from twisted.trial import util

    try:
        cfg = config.ScalemailConfig()
        authfile = os.fdopen(3, 'r')
        service = authfile.readline().rstrip()
        authtype = authfile.readline().rstrip()
        authdata = authfile.read()
        authfile.close()
        try:
            d = main(config=cfg,
                     argv=sys.argv,
                     env=os.environ,
                     service=service,
                     authtype=authtype,
                     authdata=authdata)
            r = util.wait(d, timeout=60.0)
            userdir, username = r

            switchUID(uid=pwd.getpwnam('scalemail')[2],
                      gid=grp.getgrnam('scalemail')[2])

            if not os.path.isdir(userdir):
                os.mkdir(userdir, 0700)
            os.chdir(userdir)

            if not os.path.isdir(username):
                initializeMaildir(username)
            os.chdir(username)

            os.execlp(sys.argv[1], *sys.argv[1:])
            die("Something is very wrong")
        except (error.UnauthorizedLogin,
                ChainLogin):
            # TODO pass on authinfo
            os.execlp(sys.argv[1], *sys.argv[1:])
            die("Something is very wrong")
        except RetryLogin:
            # TODO pass on authinfo
            l = []

            argc = int(os.environ['AUTHARGC'])
            for i in range(argc):
                l.append(os.environ['AUTHARGV%d' % i])
            os.execlp(*l)
            die("Something is very wrong")
    except SystemExit:
        raise
    except:
        try:
            traceback.print_exc(file=sys.stderr)
        finally:
            sys.exit(EX_TEMPFAIL)
开发者ID:tv42,项目名称:scalemail,代码行数:55,代码来源:courier_login.py


示例9: test_currentEUID

 def test_currentEUID(self):
     """
     If the current euid is the same as the euid passed to L{util.switchUID},
     then initgroups does not get called, but a warning is issued.
     """
     euid = self.mockos.geteuid()
     util.switchUID(euid, None, True)
     self.assertEqual(self.initgroupsCalls, [])
     self.assertEqual(self.mockos.seteuidCalls, [])
     warnings = self.flushWarnings([util.switchUID])
     self.assertEqual(len(warnings), 1)
     self.assertIn("tried to drop privileges and seteuid %i" % euid, warnings[0]["message"])
     self.assertIn("but euid is already %i" % euid, warnings[0]["message"])
开发者ID:ragercool,项目名称:twisted,代码行数:13,代码来源:test_util.py


示例10: test_currentUID

 def test_currentUID(self):
     """
     If the current uid is the same as the uid passed to L{util.switchUID},
     then initgroups does not get called, but a warning is issued.
     """
     uid = self.mockos.getuid()
     util.switchUID(uid, None)
     self.assertEqual(self.initgroupsCalls, [])
     self.assertEqual(self.mockos.actions, [])
     warnings = self.flushWarnings([util.switchUID])
     self.assertEqual(len(warnings), 1)
     self.assertIn('tried to drop privileges and setuid %i' % uid, 
                   warnings[0]['message'])
     self.assertIn('but uid is already %i' % uid, warnings[0]['message'])
开发者ID:jeffreybrowning,项目名称:chat-server,代码行数:14,代码来源:test_util.py


示例11: _execChild

 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:JohnDoes95,项目名称:project_parser,代码行数:16,代码来源:process.py


示例12: shedPrivileges

    def shedPrivileges(self, euid, uid, gid):
        """
        Change the UID and GID or the EUID and EGID of this process.

        @type euid: C{bool}
        @param euid: A flag which, if set, indicates that only the I{effective}
            UID and GID should be set.

        @type uid: C{int} or C{NoneType}
        @param uid: If not C{None}, the UID to which to switch.

        @type gid: C{int} or C{NoneType}
        @param gid: If not C{None}, the GID to which to switch.
        """
        if uid is not None or gid is not None:
            switchUID(uid, gid, euid)
            extra = euid and 'e' or ''
            log.msg('set %suid/%sgid %s/%s' % (extra, extra, uid, gid))
开发者ID:Almad,项目名称:twisted,代码行数:18,代码来源:_twistd_unix.py


示例13: shared_main

def shared_main(configFileName, method, *args, **kwds):

    try:
        loadConfig(configFileName)

        # Shed privileges
        if config.UserName and config.GroupName and os.getuid() == 0:
            uid = getpwnam(config.UserName).pw_uid
            gid = getgrnam(config.GroupName).gr_gid
            switchUID(uid, uid, gid)

        os.umask(config.umask)

        try:
            rootResource = getRootResource(config)
            directory = rootResource.getDirectory()
        except DirectoryError, e:
            print "Error: %s" % (e,)
            return
        setupMemcached(config)
        setupNotifications(config)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:21,代码来源:purge.py


示例14: shedPrivileges

    def shedPrivileges(self, euid, uid, gid):
        """
        Change the UID and GID or the EUID and EGID of this process.

        @type euid: C{bool}
        @param euid: A flag which, if set, indicates that only the I{effective}
            UID and GID should be set.

        @type uid: C{int} or C{NoneType}
        @param uid: If not C{None}, the UID to which to switch.

        @type gid: C{int} or C{NoneType}
        @param gid: If not C{None}, the GID to which to switch.
        """
        if uid is not None or gid is not None:
            extra = euid and 'e' or ''
            desc = '%suid/%sgid %s/%s' % (extra, extra, uid, gid)
            try:
                switchUID(uid, gid, euid)
            except OSError:
                log.msg('failed to set %s (are you root?) -- exiting.' % desc)
                sys.exit(1)
            else:
                log.msg('set %s' % desc)
开发者ID:anrysev,项目名称:twisted,代码行数:24,代码来源:_twistd_unix.py


示例15: StandardIOObserver

    observer = StandardIOObserver()
    observer.start()

    #
    # Get configuration
    #
    try:
        loadConfig(configFileName)
        setLogLevelForNamespace(None, "warn")

        # Shed privileges
        if config.UserName and config.GroupName and os.getuid() == 0:
            uid = getpwnam(config.UserName).pw_uid
            gid = getgrnam(config.GroupName).gr_gid
            switchUID(uid, uid, gid)

        os.umask(config.umask)

        config.directory = getDirectory()
        autoDisableMemcached(config)
    except ConfigurationError, e:
        usage("Unable to start: %s" % (e,))

    try:
        dbxml = AugmentXMLDB((xmlFileName,)) if not remove else None
    except IOError, e:
        usage("Could not read XML augment file: %s" % (e,))

    #
    # Start the reactor
开发者ID:azbarcea,项目名称:calendarserver,代码行数:30,代码来源:loadaugmentdb.py


示例16: shedPrivileges

def shedPrivileges(euid, uid, gid):
    if uid is not None or gid is not None:
        switchUID(uid, gid, euid)
        extra = euid and 'e' or ''
        log.msg('set %suid/%sgid %s/%s' % (extra, extra, uid, gid))
开发者ID:radical-software,项目名称:radicalspam,代码行数:5,代码来源:_twistd_unix.py


示例17: daemon


#.........这里部分代码省略.........
       a monitor sees that a pidfile exists and the process is not
       running then the monitor restarts the process.
       If you want the process to REALLY die then the
       pid file should be removed external to the program,
       e.g., by an init.d script that is passed "stop".
    """
    assert log_file is None or logfile is None, "logfile was provided for backwards " \
           "compatibility.  You cannot specify both log_file and logfile."
    if log_file is None:
        log_file = logfile

    try:
        if os.name == 'mac':
            raise NotImplementedError( "Daemonization doesn't work on macs." )

        if noisy:
            print "in daemon"

        uid = os.getuid()
        gid = os.getgid()
        if uid == 0 and username is None:
            raise Exception( "If you start with root privileges you need to "
                "provide a username argument so that daemon() can shed those "
                "privileges before returning." )
        if username:
            uid = getuid_from_username(username)
            if noisy:
                print "setting username to uid of '%s', which is %d." % ( username, uid )
            if uid != os.getuid() and os.getuid() != 0:
                raise Exception( "When specifying a uid other than your own "
                   "you must be running as root for setuid to work. "
                   "Your uid is %d, while the specified user '%s' has uid %d."
                   % ( os.getuid(), username, uid ) )
            gid = getgid_from_username(username) # uses this user's group
        if groupname:
            if noisy:
                print "setting groupname to gid of '%s', which is %d." % (groupname,gid)
            gid = getgid_from_groupname(groupname)

        pid_dir = os.path.split(pidfile)[0]
        if pid_dir and not os.path.exists(pid_dir):
            os.mkdir(pid_dir)
            os.chown(pid_dir,uid,gid)
        checkPID(pidfile)
        if use_syslog is None:
            use_syslog = sys.platform != 'darwin' and not log_file
        if log_file:
            if use_syslog:
                raise Exception( "You have specified both a log_file and "
                    "that the daemon should use_syslog.  Specify one or "
                    "the other." )
            print "Calling injectLogger"
            injectLogger(use_syslog=False, log_file = log_file, log_level = log_level,
                         capture_output = capture_output, verbose = verbose,
                         capture_stdout_name = capture_stdout_name,
                         capture_stderr_name = capture_stderr_name,
                         twisted_info_log_level = twisted_info_log_level,
                         twisted_error_log_level = twisted_error_log_level,
                         capture_stdout_log_level = capture_stdout_log_level,
                         capture_stderr_log_level = capture_stderr_log_level,
                         use_localtime = use_localtime )
        elif use_syslog:
            injectLogger(use_syslog=True, log_level = log_level, verbose = verbose,
                         capture_output = capture_output,
                         capture_stdout_name = capture_stdout_name,
                         capture_stderr_name = capture_stderr_name,
                         twisted_info_log_level = twisted_info_log_level,
                         twisted_error_log_level = twisted_error_log_level,
                         capture_stdout_log_level = capture_stdout_log_level,
                         capture_stderr_log_level = capture_stderr_log_level )
        else:
            raise Exception( "You are attempting to daemonize without a log file,"
                             "and with use_syslog set to false.  A daemon must "
                             "output to syslog, a logfile, or both." )
        if pidfile is None:
            pid_dir = os.path.join("/var/run/", app_name )
            pidfile = os.path.join( pid_dir, app_name + ".pid")
        daemonize()  # forks, moves into its own process group, forks again,
                     # middle process exits with status 0.  Redirects stdout,
                     # stderr to /dev/null.

        # I should now be a daemon.

        open(pidfile,'wb').write(str(os.getpid()))
        if not os.path.exists(pidfile):
            raise Exception( "pidfile %s does not exist" % pidfile )
        os.chmod(pidfile, stat.S_IRUSR|stat.S_IWUSR|stat.S_IROTH|stat.S_IRGRP)

        if os.getuid() == 0:
            if uid is not None or gid is not None:
                switchUID(uid, gid)
        if os.getuid() != uid:
            raise Exception( "failed to setuid to uid %d" % uid )
        if os.getgid() != gid:
            raise Exception( "failed to setgid to gid %d" % gid )
    except:
        log.exception("daemonizing may have failed")
        import traceback
        traceback.print_exc()
        raise
开发者ID:DKILLER123,项目名称:torrentflux,代码行数:101,代码来源:daemon.py


示例18: drop_privileges

 def drop_privileges(self):
     ent = pwd.getpwnam(self.conf['user'])
     switchUID(ent.pw_uid, ent.pw_gid)
开发者ID:zenweasel,项目名称:minidns,代码行数:3,代码来源:dns.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.unsignedID函数代码示例发布时间:2022-05-27
下一篇:
Python util.sibpath函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap