zoukankan      html  css  js  c++  java
  • 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;
                }
            }
    
    
    
        }
  • 相关阅读:
    浅谈树状数组与线段树
    BZOJ1367:[Baltic2004]sequence
    浅谈左偏树
    BZOJ4003:[JLOI2015]城池攻占
    BZOJ2809:[APIO2012]dispatching
    BZOJ1455:罗马游戏
    模拟ssh远程执行命令
    基于TCP协议的socket套接字编程
    计算机网络基础知识
    元类( 控制对象产生和控制类产生)模板
  • 原文地址:https://www.cnblogs.com/zyip/p/2988345.html
Copyright © 2011-2022 走看看