#!/usr/bin/perl -w
#
# changing user passwords in AD
#
use strict;
use warnings;
use Net::LDAP;
# module needed to encode AD password
use Unicode::String qw(utf8);
#
# ARGV is username password
my $username = $ARGV[0];
my $passwd = $ARGV[1];
my $result;
my $adsvr='twnlab.local';
my $adbinddn='cn=useradmin,ou=SERVICEDESK,ou=User,dc=twnlab,dc=local';
my $adpw='P@ssw0rd11';
# Connect to the AD server
#my $ad=Net::LDAP->new($adsvr, version=>3, scheme=>'ldaps', port=>636,) or die "can't connect to $adsvr: $@"); # For LDAP Windows 2008 R2
my $ad=Net::LDAP->new($adsvr, version=>3, scheme=>'ldap', port=>389,) or die "can't connect to $adsvr: $@"); # For LDAP Windows 2012 R2
# Bind as Administrator
$result=$ad->bind($adbinddn, password=>$adpw);
if ($result->code) {
LDAPerror ("binding",$result);
exit 1;
};
# check for username, get DN
$result = $ad->search(
base => "ou=User,ou=User,dc=twnlab,dc=local",
filter => "(samAccountName=$username)",
attrs => ['distinguishedName']
);
$result->code && die $result->error;
if ($result->entries != 1 ) { die "ERROR: User not found in AD: $username" };
my $entry = $result->entry(0); # there can be only one
my $dn = $entry->get_value('distinguishedName');
my $unicodePwd = utf8(chr(34).${passwd}.chr(34))->utf16le();
# change password entries etc.
#$result = $ad->modify($dn, replace => {unicodePwd=> $unicodePwd,}); #password change for 2008 AD
$result = $ad->modify($dn, replace => {userPassword=> $unicodePwd,}); #password change for 2012 AD
$result->code && die $result->error;
print "AD : SUCCESS: ${username} password changed.n";
$ad->unbind();
####
C:\script\perl> changepassword.pl user1 P@ssw0rd1234
AD : SUCCESS: user1 password changed.n
C:\script\perl>
##
##
4723 - An attempt was made to change an account's password
4724 - An attempt was made to reset an accounts password
627 - Change Password Attempt
628 - User Account password set