modify AD property and password using C#
2013-03-29 10:17
113 查看
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; } } }
相关文章推荐
- How to add, modify, or delete registry subkeys and values by using a registration entries (.reg) file
- csharp: SQL Server 2005 Database Backup and Restore using C#
- .net 操作 EXCEL (using c# to control and access the excel)
- Objective-c using @property and memory management
- Using Reflection and Expression to get Property with better performance.
- How to Modify the Password for SYSMAN and other Enterprise Manager Users at the OMS Level and Reposi
- How to serialize and deserialize using C# .NET
- C# : row-clickable GridView and get and set gridview rows using JavaScript
- [转]C# and the using Statement in 3 seconds and a bug in Reflector
- C# Best Practices - Accessing and Using Classes
- Create, Read, Write, Copy, Move and Delete a Text File using C#
- Login to Symantec Endpoint Protection Manager using your Active Directory User name and password
- How To Read and Write BLOB Data by Using ADO.NET with Visual C# .NET
- Authenticate a user against the Active Directory using the user ID and password
- Augmented Reality Using C# and OpenCV
- #150 – An Example of Using PropertyChanged and CoerceValue Callbacks(PropertyChanged和CoerceValue例子)
- How To Read and Write BLOB Data by Using ADO.NET with Visual C# .NET
- Using C# to connect to and query from a SQL database
- Printing out your W2 Form using C# and .NET
- Display MS Excel Sheets and Charts in ASPX Pages using C#[favorite]