Skip to content

Instantly share code, notes, and snippets.

@mrunyon
Created March 29, 2013 16:56
Show Gist options
  • Select an option

  • Save mrunyon/5272086 to your computer and use it in GitHub Desktop.

Select an option

Save mrunyon/5272086 to your computer and use it in GitHub Desktop.
Script to test authentication against a *nix system using PAM and pexpect. Takes 2 arguments from the command line for username and password. Modified from original to support CentOS4 more explicitly. Original source; jay_t @ stackoverflow.com : http://stackoverflow.com/questions/5286321/pam-authentication-in-python-without-root-privileges
#!/usr/bin/python
import sys, getopt, pexpect
def main(argv):
username = ''
password = ''
try:
opts, args = getopt.getopt(argv,"hu:p:",["username=","password="])
except getopt.GetoptError:
print 'check-pwd.py -u <username> -p <password>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'check-pwd.py -u <username> -p <password>'
sys.exit()
elif opt in ("-u", "--username"):
username = arg
elif opt in ("-p", "--password"):
password = arg
print pam(username=username, password=password)
def pam(username, password):
try:
child = pexpect.spawn('/bin/su - %s'%(username))
child.expect('Password:')
child.sendline(password)
result=child.expect(['su: incorrect password','Shell access is not permitted.',username])
child.expect(pexpect.EOF);
child.close()
except Exception, err:
child.close()
print ("Error authenticating. Reason: %s"%(err))
return False
if result == 0:
print ("Authentication failed for user %s."%(username))
return False
elif result == 1:
print ("Authentication succeeded for user %s."%(username))
return True
else:
print ("Authentication succeeded for user %s."%(username))
return True
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment