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


Python pwd.getpwall函数代码示例

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


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


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