Abstract how to look up user password to be more flexible

This adds user_password() to abstract how the user's password is looked
up.  If spwd is not available, this will read the shadow file for the
user's shadow entry.  This will then facilitate idempotent password
changes on hosts without spwd.
reviewable/pr18780/r1
Stephen Fromm 12 years ago
parent 70b1d00abe
commit 62a4a68658

33
user

@ -18,6 +18,7 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
import pwd import pwd
import grp import grp
try: try:
@ -26,6 +27,14 @@ try:
except: except:
HAVE_SPWD=False HAVE_SPWD=False
SHADOWFILE = '/etc/shadow'
if os.path.exists('/etc/master.passwd'):
SHADOWFILE = '/etc/master.passwd' # FreeBSD passwd
# Note: while the above has the correct location for where
# encrypted passwords are stored on FreeBSD, the code below doesn't
# invoke adduser in lieu of useradd, nor pw in lieu of usermod.
# That is, this won't work on FreeBSD.
def get_bin_path(module, arg): def get_bin_path(module, arg):
if os.path.exists('/usr/sbin/%s' % arg): if os.path.exists('/usr/sbin/%s' % arg):
return '/usr/sbin/%s' % arg return '/usr/sbin/%s' % arg
@ -198,15 +207,27 @@ def get_pwd_info(user):
def user_info(user): def user_info(user):
if not user_exists(user): if not user_exists(user):
return False return False
try:
info = get_pwd_info(user) info = get_pwd_info(user)
if len(info[1]) == 1 or len(info[1]) == 0:
info[1] = user_password(user)
return info
def user_password(user):
passwd = ''
if not user_exists(user):
return passwd
if HAVE_SPWD: if HAVE_SPWD:
sinfo = spwd.getspnam(user) try:
passwd = spwd.getspnam(user)[1]
except KeyError: except KeyError:
return False return passwd
if HAVE_SPWD: else:
info[1] = sinfo[1] # Read shadow file for user's encrypted password string
return info if os.path.exists(SHADOWFILE) and os.access(SHADOWFILE, os.R_OK):
for line in open(SHADOWFILE).readlines():
if line.startswith('%s:' % user):
passwd = line.split(':')[1]
return passwd
# =========================================== # ===========================================

Loading…
Cancel
Save