本文整理汇总了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
示例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")
示例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
示例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))
示例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)
示例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")
示例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")
示例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()
示例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
示例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)
示例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
示例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)
示例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
示例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
示例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()