Skip to content

Instantly share code, notes, and snippets.

@sjparsons
Created January 6, 2012 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sjparsons/ad0a615cec792ffe4ade to your computer and use it in GitHub Desktop.
Save sjparsons/ad0a615cec792ffe4ade to your computer and use it in GitHub Desktop.
Python script to change a user's password over Active Directory LDAP
#!/usr/bin/python
import ldap
import sys
# Input
[server, dn, cur_password, new_password] = sys.argv[1:]
# Setup Passwords
cur_pass = ('"%s"' % cur_password).encode("utf-16-le")
new_pass = ('"%s"' % new_password).encode("utf-16-le")
# Connect to LDAP
con = ldap.initialize(server)
# Bind with given dn / cur_password
try:
con.simple_bind_s(dn,cur_password)
except ldap.INVALID_CREDENTIALS:
print "invalid credentials"
sys.exit(3)
# Attempt to update password.
try:
mod_attrs = [(ldap.MOD_DELETE, 'unicodepwd', cur_pass),(ldap.MOD_ADD,'unicodepwd',new_pass)]
con.modify_s(dn, mod_attrs)
except ldap.CONSTRAINT_VIOLATION, e:
if e.args[0]['info'][5:8] == '056':
print "invalid creds (using prev password)";
sys.exit(3)
else:
print "old password"
sys.exit(4)
sys.exit()
@sjparsons
Copy link
Author

You should call passwordch.py like so:

passwordch.py ldaps://23.34.12.34 'full-dn' 'old-password' 'new-password'

Watch the return codes.

  • 0 = success
  • 3 = invalid credentials (or using the most previous password as old password)
  • 4 = the new password has been used previously
  • anything else is a problem connecting to AD ldap of find the user.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment