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


Python pwd.getpwnam函数代码示例

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


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

示例1: check_user

def check_user(user):
  print ("Checking %s user exist or not." % (user))
  try:
    pwd.getpwnam(user)
    return True
  except KeyError:
    return False
开发者ID:roshan3133,项目名称:DevOps,代码行数:7,代码来源:main.py

示例2: test_removed_mc

def test_removed_mc(ldap_conn, sanity_rfc2307):
    """
    Regression test for ticket:
    https://fedorahosted.org/sssd/ticket/2726
    """

    ent.assert_passwd_by_name(
        'user1',
        dict(name='user1', passwd='*', uid=1001, gid=2001,
             gecos='1001', shell='/bin/bash'))
    ent.assert_passwd_by_uid(
        1001,
        dict(name='user1', passwd='*', uid=1001, gid=2001,
             gecos='1001', shell='/bin/bash'))

    ent.assert_group_by_name("group1", dict(name="group1", gid=2001))
    ent.assert_group_by_gid(2001, dict(name="group1", gid=2001))
    stop_sssd()

    # remove cache without invalidation
    for path in os.listdir(config.MCACHE_PATH):
        os.unlink(config.MCACHE_PATH + "/" + path)

    # sssd is stopped; so the memory cache should not be used
    # in long living clients (py.test in this case)
    with pytest.raises(KeyError):
        pwd.getpwnam('user1')
    with pytest.raises(KeyError):
        pwd.getpwuid(1001)

    with pytest.raises(KeyError):
        grp.getgrnam('group1')
    with pytest.raises(KeyError):
        grp.getgrgid(2001)
开发者ID:3van,项目名称:sssd,代码行数:34,代码来源:test_memory_cache.py

示例3: drop_privileges

    def drop_privileges(self, uid_name=None, gid_name=None):
        """ Drop privileges
        
        Found in https://github.com/zedshaw/python-lust/blob/master/lust/unix.py
        """
        if os.getuid() != 0:
            self.logger.warning("Must be root to drop privileges!")
            return
    
        # Get the uid/gid from the name. If no group given, then derive group from uid_name
        if uid_name is None:
            uid_name = "nobody"  # builtin default is nobody
        running_uid = pwd.getpwnam(uid_name).pw_uid
        if gid_name is None:
            running_gid = pwd.getpwnam(uid_name).pw_gid
        else:
            running_gid = grp.getgrnam(gid_name).gr_gid

        self.logger.debug("Running as %r.%r" % (running_uid, running_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
        os.umask(077)
开发者ID:paramonov,项目名称:yaml-server,代码行数:29,代码来源:YamlDaemon.py

示例4: install_buildbot_slave

def install_buildbot_slave(name, path=None, script_dir='', shell=False, **args):
  username = 'vagrant'
  if platform.system() == 'Linux':
    # Create buildbot user if it doesn't exist.
    username = 'buildbot'
    import pwd
    try:
      pwd.getpwnam(username)
    except KeyError:
      check_call(['sudo', 'useradd', '--system', '--home', '/var/lib/buildbot',
                  '--create-home', '--shell', '/bin/false', 'buildbot'])
  path = path or os.path.expanduser('~{0}/slave'.format(username))
  if os.path.exists(path):
    return
  pip_install('buildbot-slave', 'buildbot')
  # The password is insecure but it doesn't matter as the buildslaves are
  # not publicly accessible.
  command = [os.path.join(script_dir, 'buildslave'),
             'create-slave', path, args.get('ip', '10.0.2.2'), name, 'pass']
  if not windows:
    command = ['sudo', '-u', username] + command
  check_call(command, shell=shell)
  if windows:
    return
  if args.get('nocron', False):
    return
  pip_install('python-crontab', 'crontab')
  from crontab import CronTab
  cron = CronTab(username)
  cron.new('PATH={0}:/usr/local/bin buildslave start {1}'.format(
    os.environ['PATH'], path)).every_reboot()
  cron.write()
  # Ignore errors from buildslave as the buildbot may not be accessible.
  call(['sudo', '-H', '-u', username, 'buildslave', 'start', path])
开发者ID:tkelman,项目名称:mp,代码行数:34,代码来源:bootstrap.py

示例5: sudo_run_background

    def sudo_run_background(self, run_as='root'):
        """
        Public method enabling the library's user to run in background a
        nmap scan with priviledges via sudo.
        The sudo configuration should be set manually on the local system
        otherwise sudo will prompt for a password.
        This method alters the command line by prefixing the sudo command to
        nmap and will then call self.run()

        :param run_as: user name to which the lib needs to sudo to run the scan

        :return: return code from nmap execution
        """
        sudo_user = run_as.split().pop()
        try:
            pwd.getpwnam(sudo_user).pw_uid
        except KeyError:
            raise

        sudo_path = self._whereis("sudo")
        if sudo_path is None:
            raise EnvironmentError(2, "sudo is not installed or "
                                      "could not be found in system path: "
                                      "cannot run nmap with sudo")

        self.__sudo_run = "{0} -u {1}".format(sudo_path, sudo_user)
        super(NmapProcess, self).start()
开发者ID:allfro,项目名称:python-libnmap,代码行数:27,代码来源:process.py

示例6: authorize

 def authorize (self, channel, username, password):
     if string.lower(username) in ['anonymous', 'ftp']:
         import pwd
         try:
             # ok, here we run into lots of confusion.
             # on some os', anon runs under user 'nobody',
             # on others as 'ftp'.  ownership is also critical.
             # need to investigate.
             # linux: new linuxen seem to have nobody's UID=-1,
             #    which is an illegal value.  Use ftp.
             ftp_user_info = pwd.getpwnam ('ftp')
             if string.lower(os.uname()[0]) == 'linux':
                 nobody_user_info = pwd.getpwnam ('ftp')
             else:
                 nobody_user_info = pwd.getpwnam ('nobody')
             channel.read_only = 1
             if self.root is None:
                 self.root = ftp_user_info[5]
             fs = filesys.unix_filesystem (self.root, '/')
             return 1, 'Anonymous Login Successful', fs
         except KeyError:
             return 0, 'Anonymous account not set up', None
     elif self.real_users:
         return unix_authorizer.authorize (
                 self,
                 channel,
                 username,
                 password
                 )
     else:
         return 0, 'User logins not allowed', None
开发者ID:0xkag,项目名称:M2Crypto,代码行数:31,代码来源:ftp_server.py

示例7: install_conf

    def install_conf(self):
        """Install configuration files"""
        assert_root()

        print("===== Copying configuration to /usr/local/etc/")
        root = pwd.getpwnam("root")
        cmsuser = pwd.getpwnam("cmsuser")
        makedir(os.path.join(USR_ROOT, "etc"), root, 0o755)
        for conf_file_name in ["cms.conf", "cms.ranking.conf"]:
            conf_file = os.path.join(USR_ROOT, "etc", conf_file_name)
            # Skip if destination is a symlink
            if os.path.islink(conf_file):
                continue
            # If the config exists, check if the user wants to overwrite it
            if os.path.exists(conf_file):
                if not ask("The %s file is already installed, "
                           "type Y to overwrite it: " % (conf_file_name)):
                    continue
            if os.path.exists(os.path.join(".", "config", conf_file_name)):
                copyfile(os.path.join(".", "config", conf_file_name),
                         conf_file, cmsuser, 0o660)
            else:
                conf_file_name = "%s.sample" % conf_file_name
                copyfile(os.path.join(".", "config", conf_file_name),
                         conf_file, cmsuser, 0o660)
开发者ID:PJeBeK,项目名称:cms,代码行数:25,代码来源:prerequisites.py

示例8: get_or_create_ids

def get_or_create_ids(username, groupname):
    """
    Get the UID and GID for a user and group, creating the user and group if necessary.
    Users are created with no login shell: if they need a shell, downstream init scripts
    should update it.
    """
    try:
        gid = grp.getgrnam(groupname).gr_gid
    except KeyError:
        logger.info("Creating group %s", groupname)
        subprocess.call(['/usr/sbin/groupadd', '-f', groupname])
        gid = grp.getgrnam(groupname).gr_gid
    try:
        uid = pwd.getpwnam(username).pw_uid
    except KeyError:
        logger.info("Creating user %s", username)
        command = '/usr/sbin/adduser'
        command_input = ['--gid', str(gid), '--shell', '/sbin/nologin', username]
        exit_code = subprocess.call([command, '--system'] + command_input)
        # if the above command fails its highly likely that we are in a Centos 5
        # system and it doesnt have `--system` option instead it has `-r`.
        if exit_code != 0:
            subprocess.call([command, '-r'] + command_input)
        uid = pwd.getpwnam(username).pw_uid
    return uid, gid
开发者ID:amplifylitco,项目名称:asiaq,代码行数:25,代码来源:acfg1.py

示例9: chown

def chown(path, user=None, group=None, recursive=False, exclude=None):
    logger.info("chown: path=%s, user=%s, group=%s, recursive=%s, exclude=%s", path, user, group, recursive, exclude)

    uid = pwd.getpwnam(user).pw_uid if user else -1
    gid = pwd.getpwnam(group).pw_gid if group else -1
    for subpath in find(path, False, exclude):
        os.chown(subpath, uid, gid)
开发者ID:kbm1422,项目名称:husky,代码行数:7,代码来源:__init__.py

示例10: tor_new_process

def tor_new_process():
    """
    Drops privileges to TOR_USER user and start a new Tor process
    """
    debian_tor_uid = getpwnam(TOR_USER).pw_uid
    debian_tor_gid = getpwnam(TOR_USER).pw_gid
    os.setgid(debian_tor_gid)
    os.setuid(debian_tor_uid)
    os.setegid(debian_tor_gid)
    os.seteuid(debian_tor_uid)
    os.environ['HOME'] = "/var/lib/tor"

    tor_process = stem.process.launch_tor_with_config(
      config = {
        'SocksPort': '6666',
        'ControlPort': '6969',
        'DNSPort': '9053',
        'DNSListenAddress': '127.0.0.1',
        'AutomapHostsOnResolve': '1',
        'AutomapHostsSuffixes': '.exit,.onion',
        'VirtualAddrNetwork': '10.192.0.0/10',
        'TransPort': '9040',
        'TransListenAddress': '127.0.0.1',
        'AvoidDiskWrites': '1',
        'WarnUnsafeSocks': '1',
      })
开发者ID:alitalia,项目名称:stem-tortp,代码行数:26,代码来源:tortp.py

示例11: create_start

def create_start(user, app_name, _here, home):
    #create bin buat manual start
    filename = "%s/bin/start-%s" % (home, app_name)
    pid_file = "%s/tmp/%s.pid" % (home, app_name)
    log_file = "%s/log/%s" % (home, app_name)
    print ("Start application:", filename)

    uid = getpwnam(user).pw_uid
    gid = getpwnam(user).pw_gid
    create_dir(filename, uid, gid)
    create_dir(pid_file, uid, gid)
    create_dir(log_file, uid, gid)
    create_dir(log_file+'/log', uid, gid)
        
    with open(filename, 'wb') as f:
        f.write('#!/bin/bash\n')
        f.write("cd {home}/iso8583-forwarder\n".format(home=home))
        f.write("python {home}/iso8583-forwarder/iso8583-forwarder.py \\\n".format(home=home))
        f.write("    --log-dir={log_file} \\\n".format(log_file=log_file))
        f.write("    --pid-file={pid_file} $1\n".format(pid_file=pid_file))
        f.close()
    os.chmod(filename, 0755)
    
    #create bin buat service
    filename = "%s/bin/%s" % (home, app_name)
    with open(filename, 'wb') as f:
        f.write('#!/usr/bin/python\n')
        f.write("{home}/bin/start-{app_name} \\\n".format(home=home, app_name=app_name))
        f.close()
    os.chmod(filename, 0755)
开发者ID:opensipkd,项目名称:iso8583-forwarder,代码行数:30,代码来源:install.py

示例12: __init__

 def __init__(self, name_or_uid = None):
     # If passed a string, assume user name
     # If passed a number, assume uid
     # If None, leave everything with a value of None
     
     # Initialize everything to None
     for i in self._fields:
         setattr(self, i, None)
     
     # Determine whether we were passed a name or a uid or a User
     if isinstance(name_or_uid, User):
         # Guessing it's a User object - clone the settings
         # Clone if user name or uid present, otherwise None
         if name_or_uid != None:
             if name_or_uid.name is not None:
                 pw_info = pwd.getpwnam(name_or_uid.name)
             else:
                 pw_info = pwd.getpwuid(name_or_uid.uid)
             self._init_with_pwd(pw_info)
     elif isinstance(name_or_uid, (int,long)):
         # Guessing it's a uid
         try:
             pw_info = pwd.getpwuid(name_or_uid)
             self._init_with_pwd(pw_info)
         except KeyError:
             self.uid = None
     elif isinstance(name_or_uid, basestring):
         # Guessing it's a user name
         try:
             pw_info = pwd.getpwnam(name_or_uid)
             self._init_with_pwd(pw_info)
         except KeyError:
             self.name = None
开发者ID:pudquick,项目名称:pymaIdentity,代码行数:33,代码来源:pymaidentity.py

示例13: create_user

def create_user(user, groups=[], comment='', options=[]):
    """
    Helper function for creating a native linux user and its required groups.

    First tries to create all the required groups. Once done the user will be
    created and added to the group.

    Arguments:
        user (string): name of the user to create
        groups (list): if empty user will be added to its own group, if only
            one entry this will be used as the users primary group, if multiple
            entries the first entry will be the primary group and the rest
            additional groups.
    """
    for group in groups:
        create_group(group)
    try:
        pwd.getpwnam(user)
    except KeyError:
        if len(comment):
            options.extend(['-c', comment])

        if len(groups) == 0:
            subprocess.call(['useradd'] + options + [user])
        elif len(groups) == 1:
            subprocess.call(['useradd', '-g', groups[0]] + options + [user])
        else:
            subprocess.call(['useradd', '-g', groups[0], '-G', ','.join(groups[1:])] + options + [user])
开发者ID:Kobus-Smit,项目名称:AmbariKave,代码行数:28,代码来源:freeipa.py

示例14: deploy_files

def deploy_files(staging_directory, instance_directory, file_list, username):
    """
    Copies the list of files from the staging directory to the instance directory.
    Will properly set permissions and setgid files based on their type.
    """

    # get uid and gid for default and problem user
    user = getpwnam(username)
    default = getpwnam(deploy_config.DEFAULT_USER)

    for f in file_list:
        # copy the file over, making the directories as needed
        output_path = join(instance_directory, f.path)
        if not os.path.isdir(os.path.dirname(output_path)):
            os.makedirs(os.path.dirname(output_path))
        shutil.copy2(join(staging_directory, f.path), output_path)

        # set the ownership based on the type of file
        if isinstance(f, ProtectedFile) or isinstance(f, ExecutableFile):
            os.chown(output_path, default.pw_uid, user.pw_gid)
        else:
            uid = default.pw_uid if f.user is None else getpwnam(f.user).pw_uid
            gid = default.pw_gid if f.group is None else getgrnam(f.group).gr_gid
            os.chown(output_path, uid, gid)

        # set the permissions appropriately
        os.chmod(output_path, f.permissions)
开发者ID:RitwikGupta,项目名称:picoCTF-shell-manager,代码行数:27,代码来源:deploy.py

示例15: touch

    def touch(self,filename) :
        open(filename, 'a').close()
 
        # Dirty hack
        uid = pwd.getpwnam(self.traineeName).pw_uid
        gid = pwd.getpwnam(self.guideName).pw_uid
        os.chown(filename,uid,gid) 
开发者ID:alexAubin,项目名称:elliot,代码行数:7,代码来源:ls.py


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