本文整理汇总了Python中spwd.getspnam函数的典型用法代码示例。如果您正苦于以下问题:Python getspnam函数的具体用法?Python getspnam怎么用?Python getspnam使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getspnam函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authenticate
def authenticate(name, password):
"""
Returns true or false depending on the success of the name-password combination using
the shadows or passwd file (The shadow file is preferred if it exists)
"""
try:
success = pam.pam().authenticate(name, password)
if success is True:
return success
except Exception as e:
logging.warning(e)
return False
if path.exists("/etc/shadow"):
try:
if six.PY3:
shadow = spwd.getspnam(name).sp_pwdp # https://docs.python.org/3.4/library/spwd.html#module-spwd
else:
shadow = spwd.getspnam(name).sp_pwd
except KeyError as e:
return False
else:
shadow = pwd.getpwnam(name).pw_passwd
salt_pattern = compile_regex(r"\$.*\$.*\$")
try:
salt = salt_pattern.match(shadow).group()
except AttributeError as a:
logging.warning(a)
return False
return crypt(password, salt) == shadow
示例2: get_user
def get_user():
for p in pwd.getpwall():
tmp = {"user":p.pw_name,"uid":p.pw_uid,"group":grp.getgrgid(p.pw_gid).gr_name}
if spwd.getspnam(p.pw_name).sp_expire == -1:
tmp["expire"] = "Never"
else:
tmp["expire"] = serial_date_to_string(spwd.getspnam(p.pw_name).sp_expire)
user.append(tmp)
return user
示例3: creds_validator
def creds_validator(username, password):
crypted_root_pwd = spwd.getspnam(username).sp_pwd
crypted_method, crypted_salt = (crypted_root_pwd.split('$')[1], crypted_root_pwd.split('$')[2])
result_str = '{0}{1}{0}{2}{0}'.format('$', crypted_method, crypted_salt)
crypted_input_passwd = crypt.crypt(password, result_str)
return crypted_input_passwd == spwd.getspnam(username).sp_pwd
示例4: info
def info(name):
'''
Return information for the specified user
CLI Example:
.. code-block:: bash
salt '*' shadow.info root
'''
try:
data = spwd.getspnam(name)
ret = {
'name': data.sp_nam,
'passwd': data.sp_pwd,
'lstchg': data.sp_lstchg,
'min': data.sp_min,
'max': data.sp_max,
'warn': data.sp_warn,
'inact': data.sp_inact,
'expire': data.sp_expire}
except KeyError:
return {
'name': '',
'passwd': '',
'lstchg': '',
'min': '',
'max': '',
'warn': '',
'inact': '',
'expire': ''}
return ret
示例5: run
def run(self, args):
if len(args) != 2:
return
old_password = args[0]
new_password = args[1]
#
# use the system to change the password
#
self._exec('/usr/sbin/chpasswd', input=f'root:{new_password}')
#
# get the new crypted password
#
shadow_info = spwd.getspnam('root')
if shadow_info:
newpw = shadow_info.sp_pwd
#
# store it in the database
#
self.owner.command('set.attr',
[ 'attr=Kickstart_PrivateRootPassword',
'value=%s' % newpw ] )
else:
print('Could not read the new password for root')
示例6: run
def run(self, args):
if len(args) != 2:
return
old_password = args[0]
new_password = args[1]
#
# use the system to change the password
#
p = subprocess.Popen(['/usr/sbin/chpasswd'],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
o, e = p.communicate('root:%s' % new_password)
#
# get the new crypted password
#
shadow_info = spwd.getspnam('root')
if shadow_info:
newpw = shadow_info.sp_pwd
#
# store it in the database
#
self.owner.command('set.attr',
[ 'attr=Kickstart_PrivateRootPassword',
'value=%s' % newpw ] )
else:
print('Could not read the new password for root')
示例7: _getCryptedPassword
def _getCryptedPassword(self, username):
try:
import spwd
except ImportError:
return self._manualGetCryptedPassword(username)
else:
return spwd.getspnam(username)[1]
示例8: test_create_user
def test_create_user(self):
users_model = UsersModel()
user_model = UserModel()
user = 'unit_test_fake_user'
passwd = 'fakepass'
group = 'unit_test_fake_group'
profile = 'unit_test_fake_profile'
common_users = users_model.get_list()
params = {'name': user, 'password': passwd,
'group': group, 'profile': profile}
with RollbackContext() as rollback:
users_model.create(params)
rollback.prependDefer(user_model.delete, user)
new_users = users_model.get_list()
self.assertEqual(len(new_users), len(common_users) + 1)
enc_passwd = spwd.getspnam(user)[1]
invalid_passwd = [None, "NP", "!", "!!", "", "LK", "*"]
self.assertNotIn(enc_passwd, invalid_passwd)
self.assertEqual(crypt.crypt(passwd, enc_passwd), enc_passwd)
示例9: check_pw
def check_pw(user, password):
"""Check the password matches local unix password on file"""
try:
hashed_pw = spwd.getspnam(user)[1]
except:
return False
return crypt.crypt(password, hashed_pw) == hashed_pw
示例10: change
def change(username, old_password, new_password):
test_old_password = check(username, old_password)
if test_old_password == 'old_password_correct':
import subprocess
password_org_fulllist = spwd.getspnam(username)[1].split('$')
try:
password_org_hash = password_org_fulllist[1]
except IndexError:
return 'user_disabled'
password_new_enq = crypt.crypt(new_password, '$' + password_org_hash + '$' + crypt.mksalt().split('$')[2][:8])
cmd = 'usermod -p ' + '\'' + password_new_enq + '\'' + ' ' + username
return_code = subprocess.call(cmd, shell=True)
if return_code == 0:
#print('pass_change_success')
return 'pass_change_success'
else:
#print('pass_change_error')
return 'pass_change_error'
elif test_old_password == 'old_password_incorrect':
return 'old_password_incorrect'
else:
return 'unknown_username'
示例11: login
def login(self, user, passwd, peer):
if user == "root" and config.OpenWebif.no_root_access.value:
# Override "no root" for logins from local/private networks
samenet = False
networks = getAllNetworks()
if networks:
for network in networks:
if ipaddress.ip_address(unicode(peer)) in ipaddress.ip_network(unicode(network), strict=False):
samenet=True
if not (ipaddress.ip_address(unicode(peer)).is_private or samenet):
return False
from crypt import crypt
from pwd import getpwnam
from spwd import getspnam
cpass = None
try:
cpass = getpwnam(user)[1]
except:
return False
if cpass:
if cpass == 'x' or cpass == '*':
try:
cpass = getspnam(user)[1]
except:
return False
return crypt(passwd, cpass) == cpass
return False
示例12: get_user_info
def get_user_info(self):
fields = ("name", "passwd", "uid", "gid", "gecos", "dir", "shell")
try:
info_tuple = pwd.getpwnam(self.resource.name)
except KeyError:
info = dict((f, None) for f in fields)
info["exists"] = False
info['disabled-login'] = False
info['disabled-password'] = False
return info
info = {"exists": True,
"disabled-login": False,
"disabled-password": False,
}
for i, field in enumerate(fields):
info[field] = info_tuple[i]
try:
shadow = spwd.getspnam(self.resource.name)
info['passwd'] = shadow.sp_pwd
if shadow.sp_pwd == "!":
info['disabled-login'] = True
except KeyError:
info['passwd'] = ''
info['disabled-login'] = False
return info
示例13: 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)
示例14: update_user
def update_user(self, user, password):
# get the username
username = user['username']
# check if the user exists, if not return silently
try:
system_user = pwd.getpwnam(username)
system_password = spwd.getspnam(username)
except KeyError:
return
# enable the user if he or she was disabled
if (system_password.sp_pwd.startswith('!')):
print 'unlocking user', username
self.call("usermod -U %s" % username)
# fetch proper password
system_password = spwd.getspnam(username)
# a flag if uid or gid have changed
uid_gid_changed = False
# check full name
fullname = self.get_full_name(user)
if (fullname != system_user.pw_gecos.decode('utf-8')):
print 'updating fullname (i.e. comment) for', username
self.call(u'usermod -c \'%s\' %s' % (fullname, username))
# check uid
if (int(user['details']['UID']) != system_user.pw_uid):
print 'updating uid for', username
self.call("usermod -u '%s' %s" % (user['details']['UID'], username))
uid_gid_changed = True
# check gid
if (int(user['details']['GID']) != system_user.pw_gid):
print 'updating gid for', username
self.call("usermod -g '%s' %s" % (user['details']['GID'], username))
uid_gid_changed = True
# check password
if (password != system_password.sp_pwd):
print 'updating password for', username
self.call("usermod -p '%s' %s" % (password, username))
return uid_gid_changed
示例15: validate_authentication
def validate_authentication(self,username,password,handler): #"""Authenticates against shadow password db; raises AuthenticationFailed in case of failed authentication."""
if username=="anonymous":
if self.anonymous_user is None: raise AuthenticationFailed(self.msg_anon_not_allowed)
else:
try: pw1=spwd.getspnam(username).sp_pwd; pw2=crypt.crypt(password,pw1)
except KeyError: raise AuthenticationFailed(self.msg_no_such_user) # no such username
else:
if pw1 != pw2: raise AuthenticationFailed(self.msg_wrong_password)