python类setuid()的实例源码

util.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def switchUID(uid, gid, euid=False):
    if euid:
        setuid = os.seteuid
        setgid = os.setegid
    else:
        setuid = os.setuid
        setgid = os.setgid
    if gid is not None:
        setgid(gid)
    if uid is not None:
        initgroups(uid, gid)
        setuid(uid)
subprocess.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _demo_posix():
    #
    # Example 1: Simple redirection: Get process list
    #
    plist = Popen(["ps"], stdout=PIPE).communicate()[0]
    print "Process list:"
    print plist

    #
    # Example 2: Change uid before executing child
    #
    if os.getuid() == 0:
        p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
        p.wait()

    #
    # Example 3: Connecting several subprocesses
    #
    print "Looking for 'hda'..."
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 4: Catch execution error
    #
    print
    print "Trying a weird file..."
    try:
        print Popen(["/this/path/does/not/exist"]).communicate()
    except OSError, e:
        if e.errno == errno.ENOENT:
            print "The file didn't exist.  I thought so..."
            print "Child traceback:"
            print e.child_traceback
        else:
            print "Error", e.errno
    else:
        print >>sys.stderr, "Gosh.  No error."
rd.py 文件源码 项目:rubber-docker 作者: Fewbytes 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def contain(command, image_name, image_dir, container_id, container_dir,
            cpu_shares, memory, memory_swap, user):
    _setup_cpu_cgroup(container_id, cpu_shares)
    _setup_memory_cgroup(container_id, memory, memory_swap)

    linux.sethostname(container_id)  # change hostname to container_id

    linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)

    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    _create_mounts(new_root)

    old_root = os.path.join(new_root, 'old_root')
    os.makedirs(old_root)
    linux.pivot_root(new_root, old_root)

    os.chdir('/')

    linux.umount2('/old_root', linux.MNT_DETACH)  # umount old root
    os.rmdir('/old_root') # rmdir the old_root dir

    # TODO: if user is set, drop privileges using os.setuid()
    #       (and optionally os.setgid()).

    os.execvp(command[0], command)
daemon.py 文件源码 项目:shadowsocksr 作者: shadowsocksr-backup 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
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)
daemon.py 文件源码 项目:ShadowSocks 作者: immqy 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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)
_UserFriendlyRNG.py 文件源码 项目:watchmen 作者: lycclsltt 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _check_pid(self):
        # Lame fork detection to remind developers to invoke Random.atfork()
        # after every call to os.fork().  Note that this check is not reliable,
        # since process IDs can be reused on most operating systems.
        #
        # You need to do Random.atfork() in the child process after every call
        # to os.fork() to avoid reusing PRNG state.  If you want to avoid
        # leaking PRNG state to child processes (for example, if you are using
        # os.setuid()) then you should also invoke Random.atfork() in the
        # *parent* process.
        if os.getpid() != self._pid:
            raise AssertionError("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()")
websocket.py 文件源码 项目:VManagePlatform 作者: welliamcao 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def daemonize(keepfd=None, chdir='/'):
        os.umask(0)
        if chdir:
            os.chdir(chdir)
        else:
            os.chdir('/')
        os.setgid(os.getgid())  # relinquish elevations
        os.setuid(os.getuid())  # relinquish elevations

        # Double fork to daemonize
        if os.fork() > 0: os._exit(0)  # Parent exits
        os.setsid()                    # Obtain new process group
        if os.fork() > 0: os._exit(0)  # Parent exits

        # Signal handling
        signal.signal(signal.SIGTERM, signal.SIG_IGN)
        signal.signal(signal.SIGINT, signal.SIG_IGN)

        # Close open files
        maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
        if maxfd == resource.RLIM_INFINITY: maxfd = 256
        for fd in reversed(range(maxfd)):
            try:
                if fd != keepfd:
                    os.close(fd)
            except OSError:
                _, exc, _ = sys.exc_info()
                if exc.errno != errno.EBADF: raise

        # Redirect I/O to /dev/null
        os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdin.fileno())
        os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdout.fileno())
        os.dup2(os.open(os.devnull, os.O_RDWR), sys.stderr.fileno())
start_script.py 文件源码 项目:fuel-ccp-entrypoint 作者: openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def preexec_fn(user_uid, user_gid, user_home):
    def result():
        os.setgid(user_gid)
        os.setuid(user_uid)
        os.environ["HOME"] = user_home
    return result
_UserFriendlyRNG.py 文件源码 项目:aws-cfn-plex 作者: lordmuffin 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _check_pid(self):
        # Lame fork detection to remind developers to invoke Random.atfork()
        # after every call to os.fork().  Note that this check is not reliable,
        # since process IDs can be reused on most operating systems.
        #
        # You need to do Random.atfork() in the child process after every call
        # to os.fork() to avoid reusing PRNG state.  If you want to avoid
        # leaking PRNG state to child processes (for example, if you are using
        # os.setuid()) then you should also invoke Random.atfork() in the
        # *parent* process.
        if os.getpid() != self._pid:
            raise AssertionError("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()")
serverthread.py 文件源码 项目:pysshrp 作者: ybulach 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self, request, client_address, server):
        # Change user and group (only when runned as root)
        if (os.getgid() == 0) and pysshrp.common.config.userId:
            os.setgid(pysshrp.common.config.userId)
        if (os.getuid() == 0) and pysshrp.common.config.groupId:
            os.setuid(pysshrp.common.config.groupId)

        SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
_UserFriendlyRNG.py 文件源码 项目:git_intgrtn_aws_s3 作者: droidlabour 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _check_pid(self):
        # Lame fork detection to remind developers to invoke Random.atfork()
        # after every call to os.fork().  Note that this check is not reliable,
        # since process IDs can be reused on most operating systems.
        #
        # You need to do Random.atfork() in the child process after every call
        # to os.fork() to avoid reusing PRNG state.  If you want to avoid
        # leaking PRNG state to child processes (for example, if you are using
        # os.setuid()) then you should also invoke Random.atfork() in the
        # *parent* process.
        if os.getpid() != self._pid:
            raise AssertionError("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()")
subprocess.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def _demo_posix():
    #
    # Example 1: Simple redirection: Get process list
    #
    plist = Popen(["ps"], stdout=PIPE).communicate()[0]
    print "Process list:"
    print plist

    #
    # Example 2: Change uid before executing child
    #
    if os.getuid() == 0:
        p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
        p.wait()

    #
    # Example 3: Connecting several subprocesses
    #
    print "Looking for 'hda'..."
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 4: Catch execution error
    #
    print
    print "Trying a weird file..."
    try:
        print Popen(["/this/path/does/not/exist"]).communicate()
    except OSError, e:
        if e.errno == errno.ENOENT:
            print "The file didn't exist.  I thought so..."
            print "Child traceback:"
            print e.child_traceback
        else:
            print "Error", e.errno
    else:
        print >>sys.stderr, "Gosh.  No error."
util.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def set_owner_process(uid, gid):
    """ set user and group of workers processes """
    if gid:
        # versions of python < 2.6.2 don't manage unsigned int for
        # groups like on osx or fedora
        gid = abs(gid) & 0x7FFFFFFF
        os.setgid(gid)
    if uid:
        os.setuid(uid)
subprocess.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _demo_posix():
    #
    # Example 1: Simple redirection: Get process list
    #
    plist = Popen(["ps"], stdout=PIPE).communicate()[0]
    print "Process list:"
    print plist

    #
    # Example 2: Change uid before executing child
    #
    if os.getuid() == 0:
        p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
        p.wait()

    #
    # Example 3: Connecting several subprocesses
    #
    print "Looking for 'hda'..."
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 4: Catch execution error
    #
    print
    print "Trying a weird file..."
    try:
        print Popen(["/this/path/does/not/exist"]).communicate()
    except OSError, e:
        if e.errno == errno.ENOENT:
            print "The file didn't exist.  I thought so..."
            print "Child traceback:"
            print e.child_traceback
        else:
            print "Error", e.errno
    else:
        print >>sys.stderr, "Gosh.  No error."
daemon.py 文件源码 项目:aerospike-telemetry-agent 作者: aerospike 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def demote(self):
        # demote root user to any specified user or group
        try:
            if os.getuid() == 0:
                # drop supplementary groups
                os.setgroups([])
                if self.group:
                    try:
                        os.setgid(self.the_grp.gr_gid)
                    except Exception, ex:
                        logging.critical("failed to set group to \"%s\" [%s]" % (self.group, str(ex)))
                        sys.exit(1)
                if self.user:
                    try:
                        the_pwd = pwd.getpwnam(self.user)
                        os.setuid(self.the_pwd.pw_uid)
                    except Exception, ex:
                        logging.critical("failed to set user to \"%s\" [%s]" % (self.user, str(ex)))
                        sys.exit(1)
            else:
                if self.user or self.group:
                    logging.critical('not privileged ~~ cannot change to user [%s] / group [%s]' % (self.user, self.group))
                    sys.exit(1)
        except Exception, ex:
            logging.critical("daemon.demote() caught exception [%s]" % str(ex))
            sys.exit(1)
postinstall.py 文件源码 项目:ArcGIS-Enterprise-One-Click-Install 作者: crazyxhz 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def config_datastore():
    print u'---------------------------------------------------------------------------------------------'
    print u'                                      ????DataStore'
    print u'---------------------------------------------------------------------------------------------'
    if not os.path.isdir("/home/" + username + "/arcgis/datastore/usr/arcgisdatastore"):
        # newuid = pwd.getpwnam(username).pw_uid
        # os.setuid(newuid)
        os.system('sudo -u ' + username + ' mkdir -p ' + "/home/" + username + "/arcgis/datastore/usr/arcgisdatastore")
        os.system(
            'sudo -u ' + username + ' bash /home/' + username + '/arcgis/datastore/tools/configuredatastore.sh https://' + fqdn + ':6443/arcgis/admin ' + username + ' ' + passwd + ' /home/' + username + '/arcgis/datastore/usr/arcgisdatastore --stores relational,tileCache')

        print u'---------------------------------------------------------------------------------------------'
        print u'                                      DataStore????'
        print u'---------------------------------------------------------------------------------------------'
_UserFriendlyRNG.py 文件源码 项目:MCSManager-fsmodule 作者: Suwings 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _check_pid(self):
        # Lame fork detection to remind developers to invoke Random.atfork()
        # after every call to os.fork().  Note that this check is not reliable,
        # since process IDs can be reused on most operating systems.
        #
        # You need to do Random.atfork() in the child process after every call
        # to os.fork() to avoid reusing PRNG state.  If you want to avoid
        # leaking PRNG state to child processes (for example, if you are using
        # os.setuid()) then you should also invoke Random.atfork() in the
        # *parent* process.
        if os.getpid() != self._pid:
            raise AssertionError("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()")
anticrash.py 文件源码 项目:TGCli-Anticrash 作者: Dragon-Born 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def signal_handler(signal, frame):
        print('stopping script')
        os.setuid(0)
        for x in data:
            try:
                os.kill(int(data[x]['pid']), 9)
                print('killing ' + x)
            except:
                pid_not_found = True
        print("Byebye...")
        f = open('.proc','w+')
        f.write('0')
        f.close()
        wipe = subprocess.Popen(["screen", "-wipe"], stdout=subprocess.PIPE)
        os.kill(os.getpid(), 9)
daemon.py 文件源码 项目:ssrr 作者: do21 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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)
daemon.py 文件源码 项目:shadowsocksr 作者: ShadowsocksR-Live 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号