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

Python pwd.getpwall函数代码示例

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

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



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

示例1: get_users

def get_users():
    dict = {}
    #find current users and add to the the dictionary
    try:    
        users = psutil.users()

        names = []
        for user in users:
            names.append(user[0])
        dict['current_users'] = names
    except:
        print "Current Users not found"

    #find all users
    try:    
        all_users = []
        for p in pwd.getpwall():
            all_users.append(p[0])
        dict['all_users'] = all_users
    except:
        print "All Users not found"


    #make a dict of the groups of all the users
    try:
        groups = {}
        for p in pwd.getpwall():
            groups[p[0]] = grp.getgrgid(p[3])[0] 
        dict['groups'] = groups
    except:
        print "Groups not found"

    return dict
开发者ID:tbenz9,项目名称:tory,代码行数:33,代码来源:user.py


示例2: create_user

 def create_user(self, user, uid):
     """
     Create the user on the system. If the user and the uid doesn't exist, simply create it.
     If the uid is not used, but user exists, modify existing user to set the appropriate uid.
     If the uid is used, but user doesn't exists, rename existing user and create home directory.
     """
     if uid:
         uid_str = " -u " + str(uid) + " "
         # if uid doesn't exist on the system
         if int(uid) not in [x[2] for x in pwd.getpwall()]:
             # if user doesn't exist on the system
             if user not in [y[0] for y in pwd.getpwall()]:
                 cmd="useradd " + user + uid_str + " -m"
                 os.system(cmd)
             else:
                 cmd="usermod " + uid_str + user
                 os.system(cmd)
         else:
             # get username with uid
             for existing_user in pwd.getpwall():
                 if existing_user[2] == int(uid):
                     user_name = existing_user[0]
             cmd="mkdir -p /home/" + user + " && usermod --home /home/" + user + " --login " + user + " " + str(user_name) + " && chown -R " + user + " /home/" + user
             os.system(cmd)
     else:
         if user not in [x[0] for x in pwd.getpwall()]:
             cmd="useradd " + user + " -m"
             os.system(cmd)
         else:
             print("user already exists")
开发者ID:bpinto,项目名称:docker-magic-sync,代码行数:30,代码来源:config_sync.py


示例3: get_users

    def get_users (self):
        """Return the list of users on the system. These should
        be real users - i.e. should not include system users
        like nobody, gdm, nfsnobody etc.
        """
        list = []
        try:
            users = pwd.getpwall()
        except:
            raise UserDatabaseException(_("Failed to get the user list"))

        for user in pwd.getpwall():
            try:
                # remove non-users
                if user[2] < 500:
                    continue
                if user[0] in list:
                    continue
                if user[6] == "" or string.find(user[6], "nologin") != -1:
                    continue
                if user[0][len (user[0]) - 1] == "$":  # Active Directory hosts end in "$"; we don't want to show those as users
                    continue
                list.append(user[0])
            except:
                pass
        return list
开发者ID:federicomenaquintero,项目名称:sabayon,代码行数:26,代码来源:userdb.py


示例4: testGetPasswdMap

    def testGetPasswdMap(self):
        """Verify we build a correct password map from nss calls."""

        foo = ("foo", "x", 10, 10, "foo bar", "/home/foo", "/bin/shell")
        bar = ("bar", "x", 20, 20, "foo bar", "/home/monkeyboy", "/bin/shell")

        self.mox.StubOutWithMock(pwd, "getpwall")
        pwd.getpwall().AndReturn([foo, bar])

        entry1 = passwd.PasswdMapEntry()
        entry1.name = "foo"
        entry1.uid = 10
        entry1.gid = 10
        entry1.gecos = "foo bar"
        entry1.dir = "/home/foo"
        entry1.shell = "/bin/shell"

        entry2 = passwd.PasswdMapEntry()
        entry2.name = "bar"
        entry2.uid = 20
        entry2.gid = 20
        entry2.gecos = "foo bar"
        entry2.dir = "/home/monkeyboy"
        entry2.shell = "/bin/shell"

        self.mox.ReplayAll()

        password_map = nss.GetPasswdMap()

        self.assertTrue(isinstance(password_map, passwd.PasswdMap))
        self.assertEquals(len(password_map), 2)
        self.assertTrue(password_map.Exists(entry1))
        self.assertTrue(password_map.Exists(entry2))
开发者ID:robbat2,项目名称:nsscache,代码行数:33,代码来源:nss_test.py


示例5: test_get_group_list

    def test_get_group_list(self):
        user = pwd.getpwall()[0].pw_name
        primary_group = grp.getgrgid(pwd.getpwall()[0].pw_gid).gr_name
        config = {
            "regex": "(?P<account>.*)-(?P<role>.*)"
        }

        provider = Provider(user, config)
        received_groups = provider.get_group_list()
        self.assertIn(primary_group, received_groups)
开发者ID:ImmobilienScout24,项目名称:afp-core,代码行数:10,代码来源:libsss_provider_tests.py


示例6: create_user

def create_user(d_user):
    info("Create domogik user")
    if d_user not in [x[0] for x in pwd.getpwall()]:
        print("Creating the {0} user".format(d_user))
        debug('/usr/sbin/useradd --system {0}'.format(d_user))
        os.system('/usr/sbin/useradd --system {0}'.format(d_user))
        debug('/usr/sbin/usermod -a -G dialout {0}'.format(d_user))
        os.system('/usr/sbin/usermod -a -G dialout {0}'.format(d_user))
    if d_user not in [x[0] for x in pwd.getpwall()]:
        fail("Failed to create domogik user")
    else:
        ok("Correctly created domogik user")
开发者ID:cedric-bollini,项目名称:domogik,代码行数:12,代码来源:install.py


示例7: create_user

def create_user(d_user, d_shell = "/bin/sh"):
    if d_user not in [x[0] for x in pwd.getpwall()]:
        print("Creating the {0} user and add it to dialout".format(d_user))
        cmd_line = 'adduser --system {0} --shell {1} '.format(d_user, d_shell)
        debug(cmd_line)
        os.system(cmd_line)
        cmd_line = 'adduser {0} dialout'.format(d_user)
        debug(cmd_line)
        os.system(cmd_line)
    if d_user not in [x[0] for x in pwd.getpwall()]:
        fail("Failed to create domogik-mq user")
    else:
        ok("Correctly created domogik-mq user")
开发者ID:domogik,项目名称:domogik-mq,代码行数:13,代码来源:install.py


示例8: testPersistentBackup

    def testPersistentBackup(self):

        with MonkeyPatchScope([
            (netinfo, 'NET_CONF_BACK_DIR',
             os.path.join(self._tempdir, 'netback')),
            (netinfo, 'NET_CONF_DIR', self._tempdir),
            (netinfo, 'NET_CONF_PREF',
             os.path.join(self._tempdir, 'ifcfg-')),
            (ifcfg, 'ifdown', lambda x: 0),
            (ifcfg, '_exec_ifup', lambda *x: 0),
            (libvirt, 'createNetwork', lambda *x: None),
            (libvirt, 'removeNetwork', lambda *x: None),
        ]):
            # after vdsm package is installed, the 'vdsm' account will be
            # created if no 'vdsm' account, we should skip this test
            if 'vdsm' not in [val.pw_name for val in pwd.getpwall()]:
                raise SkipTest("'vdsm' is not in user account database, "
                               "install vdsm package to create the vdsm user")

            self._createFiles()

            for fn, _, _ in self._files:
                self._cw._persistentBackup(fn)

            self._makeFilesDirty()

            self._cw.restorePersistentBackup()

            self._assertFilesRestored()
开发者ID:carriercomm,项目名称:vdsm,代码行数:29,代码来源:netconfTests.py


示例9: getUser

	def getUser(self,mess,a): # %nss getUser pw_uid=1000 pw_name=stud
		s=''
		p=None
		print a
		try:
			if (a.has_key('pw_uid')):
				p=pwd.getpwuid(a['pw_uid'])
			elif (a.has_key('pw_name')):
				p=pwd.getpwnam(a['pw_name'])
			else:
				users=pwd.getpwall()
				i=0
				while (i<len(users)):
					users[i]=self.pwdStructToDict(users[i])
					i+=1
				s='@'+mess.getID()+'\n'+self.d.packData(users,'json')
		except:
			p=None
		if (s==''):
			if (p!=None):
				s='@'+mess.getID()+'\n'+self.d.packData(self.pwdStructToDict(p))
			else:
				s='@'+mess.getID()+'\n'+'success=false'
		out=xmpp.Message(mess.getFrom(),s)
		mid=self.d.genId()
		out.setID(mid)
		return out
开发者ID:PGArchangel,项目名称:JabberNet,代码行数:27,代码来源:nss.py


示例10: _ownership_update

	def _ownership_update(self):
		"""Update owner and group"""
		stat = self._provider.get_stat(self._path)

		self._combobox_owner.handler_block_by_func(self._ownership_changed)
		self._combobox_group.handler_block_by_func(self._ownership_changed)

		# remove old entries
		self._list_owner.clear()
		self._list_group.clear()

		# for local file system fill comboboxes with available user and group names
		if self._provider.is_local:
			for i, user in enumerate(pwd.getpwall()):
				self._list_owner.append((user.pw_name, user.pw_uid))
				if user.pw_uid == stat.user_id:
					self._combobox_owner.set_active(i)

			for i, group in enumerate(grp.getgrall()):
				self._list_group.append((group.gr_name, group.gr_gid))
				if group.gr_gid == stat.group_id:
					self._combobox_group.set_active(i)

		# for remote file systems simply set owner and group
		else:
			self._list_owner.append((stat.user_id, stat.user_id))
			self._list_group.append((stat.group_id, stat.group_id))
			self._combobox_owner.set_active(0)
			self._combobox_group.set_active(0)

		self._combobox_owner.handler_unblock_by_func(self._ownership_changed)
		self._combobox_group.handler_unblock_by_func(self._ownership_changed)
开发者ID:Alwnikrotikz,项目名称:sunflower-fm,代码行数:32,代码来源:properties_window.py


示例11: distribute_configs

	def distribute_configs(self):
		global idstart
		for p in pwd.getpwall():
			if p[2] >= idstart:
				home = p[5]
				# If user has set profile id, then copy settings
				if (int(p[2]) in self.data['user_profiles']):
					profile_id = self.data['user_profiles'][int(p[2])]
					profile_settings = self.data['profiles'][profile_id]
					try:
						pickle.dump(profile_settings, open(home+"/.btw_settings.p", "wb"))
					except:
						pass
				elif (int(p[3]) in self.data['group_profiles']):
					profile_id = self.data['group_profiles'][int(p[3])]
					profile_settings = self.data['profiles'][profile_id]
					try:
						pickle.dump(profile_settings, open(home+"/.btw_settings.p", "wb"))
					except:
						pass
				else:
					try:
						pickle.dump({}, open(home+"/.btw_settings.p", "wb"))
					except:
						pass

				try:
					os.chown(home+"/.btw_settings.p", p[2], p[3])
				except:
					pass
开发者ID:mafrez,项目名称:BanTheWeb,代码行数:30,代码来源:main.py


示例12: UserAdd_Shadow

def UserAdd_Shadow(User, Passwodr='*', ExpireDays=-1, ShadowFile='/etc/shadow'):
	# 1. temporary shadow file
	fd, TempShadowFile = mkstemp(prefix='shadow', dir='/tmp')

	# 2. get users passwd entries
	pwall = pwd.getpwall()
	pwall.sort(lambda a, b: cmp(a.pw_uid, b.pw_uid))

	# 3. generate shadow entries
	CreatedDays = int(time() / 86400)
	if ExpireDays != -1:
		ExpireDays = CreatedDays + ExpireDays

	spall = []
	for pw in pwall:
		try:
			sp = spwd.getspnam(pw.pw_name)
		except KeyError, e:
			sp = spwd.struct_spwd(
				sequence = (
					User,
					'*',
					CreatedDays,
					0,
					99999,
					7,
					-1,
					ExpireDays,
					-1))
		spall.append(sp)
开发者ID:duke-cheng,项目名称:jail,代码行数:30,代码来源:user.py


示例13: map_uids_to_names

def map_uids_to_names():
    """Determine the mapping between user ids and user names."""
    ul = pwd.getpwall()
    d = {}
    for u in ul:
        d[u[2]] = u[0]
    return d
开发者ID:boegel,项目名称:vsc-filesystems,代码行数:7,代码来源:dquota.py


示例14: enum_instances

 def enum_instances(self, env, model, keys_only):
     self._logger.log_debug("\n%s:  enum_instances called for class %s" % (self.__class__.__name__.upper(), model.classname))
     for pwent in pwd.getpwall():
         user_cin = pywbem.CIMInstanceName('TestAssoc_User',
                 namespace=model.path.namespace)
         group_cin = pywbem.CIMInstanceName('TestAssoc_Group',
                 namespace=model.path.namespace)
         model['Dependent'] = get_user_instance(pwent[2], user_cin, True)
         model.path['Dependent'] = get_user_instance(pwent[2], 
                 user_cin, True)
         model['Antecedent'] = get_group_instance(pwent[3], group_cin, True)
         model.path['Antecedent'] = get_group_instance(pwent[3], 
                 group_cin, True)
         if not keys_only:
             model['isPrimaryGroup'] = True
         yield model
         for grent in grp.getgrall():
             if pwent[0] in grent[3]:
                 model['Antecedent'] = get_group_instance(grent[2], 
                         group_cin, True)
                 model.path['Antecedent'] = get_group_instance(grent[2], 
                         group_cin, True)
                 if not keys_only:
                     model['isPrimaryGroup'] = False
                 yield model
开发者ID:alexanderlaw,项目名称:cmpi-bindings,代码行数:25,代码来源:TestAssocProvider.py


示例15: initUI

    def initUI(self, class_sel):

        # == update system user list ==
        self.userList=pwd.getpwall()
    
        # == populate classed combo ==
        self.lstClasses.clear()
        pos=0
        idx_sel = 0
        
        for i in range(ord('a'), ord('p')+1):
            
            self.lstClasses.addItem("classe_1%s"%chr(i))
            self.lstClasses.addItem("classe_2%s"%chr(i))
            self.lstClasses.addItem("classe_3%s"%chr(i))
            pos=pos+1
            
        # == table properties ==
        self.tableStudents.setColumnCount(2)
        self.tableStudents.setRowCount(0)
        self.tableStudents.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.tableStudents.setHorizontalHeaderLabels(['Nome Completo', 'username'])
        self.tableStudents.setColumnWidth(0,400)
        self.tableStudents.setColumnWidth(1,300)
        self.tableStudents.setSortingEnabled(True)
        
        
        # == update table with last class ==
        if class_sel != '' :
            pos = self.lstClasses.findText(class_sel)
            if pos >= 0 :
                self.lstClasses.setCurrentIndex(pos)
        self.updateTable()
开发者ID:itarozzi,项目名称:classerman,代码行数:33,代码来源:studentmanager.py


示例16: complete_files

        def complete_files(self, text, state):
            str_delim = text[0]
            path = text[1:]

            if path.startswith("~/"):
                path = expanduser("~/") + path[2:]

            elif path.startswith("~"):
                i = path.find(pathsep)
                if i > 0:
                    path = expanduser(path[:i]) + path[i:]
                else:
                    return [
                        str_delim + "~" + i[0] + pathsep
                        for i in getpwall()
                        if i[0].startswith(path[1:])
                        ][state]

            dir, fname = splitpath(path)
            if not dir:
                dir = os.curdir
            return [
                str_delim + joinpath(dir, i)
                for i in os.listdir(dir)
                if i.startswith(fname)
                ][state]
开发者ID:0xf4,项目名称:pythonrc,代码行数:26,代码来源:pythonrc.py


示例17: uid_list

 def uid_list(self):
     """Lists all UIDs on the target system(s)."""
     uids = []
     for user in pwd.getpwall():
         if user[2] < 4294967294:
             uids.append(user[2])
     return uids
开发者ID:caglar10ur,项目名称:func,代码行数:7,代码来源:users.py


示例18: get_users

def get_users(exclude_system_users=True):
    if exclude_system_users:
        return [user.pw_name for user in pwd.getpwall()
                if user.pw_uid >= 1000]

    admin = libuser.admin()
    return admin.enumerateUsers()
开发者ID:MalleshKoti,项目名称:ginger,代码行数:7,代码来源:users.py


示例19: UpdateAccounts

  def UpdateAccounts(self):
    """Update all accounts that should be present or exist already."""

    # Note GetDesiredAccounts() returns a dict of username->sshKeys mappings.
    desired_accounts = self.desired_accounts.GetDesiredAccounts()

    # Plan a processing pass for extra accounts existing on the system with a
    # ~/.ssh/authorized_keys file, even if they're not otherwise in the metadata
    # server; this will only ever remove the last added-by-Google key from
    # accounts which were formerly in the metadata server but are no longer.
    all_accounts = pwd.getpwall()
    keyfile_suffix = os.path.join('.ssh', 'authorized_keys')
    sshable_usernames = [
        entry.pw_name
        for entry in all_accounts
        if os.path.isfile(os.path.join(entry.pw_dir, keyfile_suffix))]
    extra_usernames = set(sshable_usernames) - set(desired_accounts.keys())

    if desired_accounts:
      for username, ssh_keys in desired_accounts.iteritems():
        if not username:
          continue

        self.accounts.UpdateUser(username, ssh_keys)

    for username in extra_usernames:
      # If a username is present in extra_usernames, it is no longer reflected
      # in the metadata server but has an authorized_keys file. Therefore, we
      # should pass the empty list for sshKeys to ensure that any Google-managed
      # keys are no longer authorized.
      self.accounts.UpdateUser(username, [])
开发者ID:OddBloke,项目名称:compute-image-packages,代码行数:31,代码来源:accounts_manager.py


示例20: dir_chown

    def dir_chown(self, directories, user, group, recursive=False):
        """
        Chown a or multiple directories
        :param directories: Directories to chown
        :param user: User to assign to directories
        :param group: Group to assign to directories
        :param recursive: Chown the directories recursively or not
        :return: None
        """
        all_users = [user_info[0] for user_info in pwd.getpwall()]
        all_groups = [group_info[0] for group_info in grp.getgrall()]

        if user not in all_users:
            raise ValueError('User "{0}" is unknown on the system'.format(user))
        if group not in all_groups:
            raise ValueError('Group "{0}" is unknown on the system'.format(group))

        uid = pwd.getpwnam(user)[2]
        gid = grp.getgrnam(group)[2]
        if isinstance(directories, basestring):
            directories = [directories]
        for directory in directories:
            directory = self.shell_safe(directory)
            os.chown(directory, uid, gid)
            if recursive is True:
                for root, dirs, _ in os.walk(directory):
                    for sub_dir in dirs:
                        os.chown('/'.join([root, sub_dir]), uid, gid)
开发者ID:DarumasLegs,项目名称:alba-asdmanager,代码行数:28,代码来源:localclient.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python pwd.getpwnam函数代码示例发布时间:2022-05-25
下一篇:
Python meta.Session类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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