modify AD property and password using C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.DirectoryServices;

namespace ConsoleApplication1
{

    public class Helper
    {
        public static string path = "LDAP://192.168.8.1";   //the IP address point to your domain server 
        public static string admin = "administrator";       //administrator name
        public static string pwd = "Abcdefg";               //the password for the previous user

        //create a random password,it at least has 3 characters
        //the first character is a upper letter
        //the second character is a special letter,such as !,@,# ...
        //the reset of the characters are lower letters
        public static string GetRandomPassword(int passwordLen)
        {
            System.Threading.Thread.Sleep(15);
            string randomChars1 = "abcdefghijklmnopqrstuvwxyz";
            string randomChars2 = randomChars1.ToUpper();
            string randomChars3 = "!@#$%^&*()";
            string randomChars = randomChars1;
            string password = string.Empty;
            int randomNum;
            Random random = new Random();

            randomNum = random.Next(randomChars2.Length);
            password += randomChars2[randomNum];
            randomNum = random.Next(randomChars3.Length);
            password += randomChars3[randomNum];
            for (int i = 0; i < passwordLen - 2; i++)
            {
                randomNum = random.Next(randomChars.Length);
                password += randomChars[randomNum];
            }

            return password;
        }

        //reset password
        //len is then length of your new password
        public static string RestPwd(string name, int len)
        {
            string pwd = GetRandomPassword(len);
            RestPwd(name, pwd);
            return pwd;
        }

        //use a specified to change your password
        public static void RestPwd(string name,string newPwd)
        {

            var directoryEntry = FindByName(name);
            directoryEntry.Invoke("SetPassword", new object[] { newPwd });
            directoryEntry.Properties["LockOutTime"].Value = 0;
            directoryEntry.Close();
        }

        public static DirectoryEntry createDirectoryEntry(string admin, string pwd)
        {
            DirectoryEntry ldapConnection = new DirectoryEntry();
            ldapConnection.Path = path;
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            ldapConnection.Username = admin;
            ldapConnection.Password = pwd;
            return ldapConnection;
        }

        public static DirectoryEntry FindByName(string name)
        {
            var de = createDirectoryEntry(admin, pwd);
            DirectorySearcher search = new DirectorySearcher(de);
            if (name.Contains(" "))
            {
                search.Filter = "(cn=" + name + ")";//this is a display name,it usually contains a ' ',for instance:'Jack Brown'
            }
            else
            {
                search.Filter = "(mailNickname=" + name + ")";//the email,for instance:'jackbrown'
            }
            SearchResult result = search.FindOne();
            if (result != null)
                return result.GetDirectoryEntry();
            else
                return null;
        }


        //modify mobile number
        public static bool SetMobile(string name, string mobile)
        {
            try
            {
                var de = FindByName(name);
                de.Properties["mobile"].Value = mobile;
                de.CommitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }



    }


}

 ============在web环境下 需要提升权限来运行================

===========You have to improve your permission(impersonate an administrator) ==========================

 

    public class Helper
    {
        //public static string path = "LDAP://192.168.8.1";   //the IP address point to your domain server 
        public static string path = "LDAP://192.168.8.96";   //the IP address point to your domain server 
        public static string admin = "administrator";       //administrator name
        public static string domain = "Abc.local";             //domain name
        public static string pwd = "abcdefg";               //the password for the previous user

        //create a random password,it at least has 3 characters
        //the first character is a upper letter
        //the second character is a special letter,such as !,@,# ...
        //the reset of the characters are lower letters
        public static string GetRandomPassword(int passwordLen)
        {
            System.Threading.Thread.Sleep(15);
            string randomChars1 = "abcdefghijklmnopqrstuvwxyz";
            string randomChars2 = randomChars1.ToUpper();
            string randomChars3 = "!@#$%^&*()";
            string randomChars = randomChars1;
            string password = string.Empty;
            int randomNum;
            Random random = new Random();

            randomNum = random.Next(randomChars2.Length);
            password += randomChars2[randomNum];
            randomNum = random.Next(randomChars3.Length);
            password += randomChars3[randomNum];
            for (int i = 0; i < passwordLen - 2; i++)
            {
                randomNum = random.Next(randomChars.Length);
                password += randomChars[randomNum];
            }

            return password;
        }

        //reset password
        //len is then length of your new password
        public static string RestPwd(string name, int len)
        {
            string pwd = GetRandomPassword(len);
            if (RestPwd(name, pwd))
                return pwd;
            else
                return null;
        }

        //use a specified to change your password
        public static bool RestPwd(string name, string newPwd)
        {
            bool result = true;
            try
            {
                IntPtr accessToken = IntPtr.Zero;
                if (LogonUser(Helper.admin, Helper.domain, Helper.pwd, LOGON_TYPE_INTERACTIVE, LOGON_TYPE_PROVIDER_DEFAULT, ref accessToken))
                {
                    using (WindowsIdentity identity = new WindowsIdentity(accessToken))
                    {
                        using (WindowsImpersonationContext context = identity.Impersonate())
                        {

                            var directoryEntry = FindByName(name);
                            if (directoryEntry != null)
                            {

                                directoryEntry.Invoke("SetPassword", new object[] { newPwd });
                                directoryEntry.Properties["LockOutTime"].Value = 0;
                                directoryEntry.Close();
                            }

                        }
                    }
                }
            }
            catch(Exception ex){
                result=false;
            }
            return result;

        }

        public static DirectoryEntry createDirectoryEntry(string admin, string pwd)
        {
            DirectoryEntry ldapConnection = new DirectoryEntry();
            ldapConnection.Path = path;
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            ldapConnection.Username = admin;
            ldapConnection.Password = pwd;
            return ldapConnection;
        }

        public static DirectoryEntry FindByName(string name)
        {
            var de = createDirectoryEntry(admin, pwd);
            DirectorySearcher search = new DirectorySearcher(de);
            if (!name.Contains(" "))
            {
                search.Filter = "(cn=" + name + ")";//this is a display name,it usually contains a ' ',for instance:'Jack Brown'
                //HttpContext.Current.Response.Write("search.Filter:" + search.Filter);
            }
            else
            {
                search.Filter = "(mailNickname=" + name + ")";//the email,for instance:'jackbrown'
                //HttpContext.Current.Response.Write("search.Filter:" + search.Filter);
            }
            SearchResult result = search.FindOne();
            if (result != null)
            {
                return result.GetDirectoryEntry();
            }
            else
            {
                return null;
            }
        }


        //modify mobile number
        public static bool SetMobile(string name, string mobile)
        {
            try
            {
                var de = FindByName(name);
                de.Properties["mobile"].Value = mobile;
                de.CommitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }



    }

 

posted @ 2013-03-29 10:17  zyip  阅读(500)  评论(0编辑  收藏  举报