更新时间:2023-09-28 21:57:04
您可以使用以下代码从AD中获取登录的用户ID,如下所示:
You can use the below code to fetch the logged IN user ID from AD as:
WindowsIdentity ident = WindowsIdentity.GetCurrent();
WindowsPrincipal user = new WindowsPrincipal(ident);
string username = StripDomainFromUserName(user.Identity.Name);
using (DirectoryEntry de = new DirectoryEntry("LDAP://" + StripDomain(user.Identity.Name)))
{
using (DirectorySearcher adSearch = new DirectorySearcher(de))
{
adSearch.Filter = "(DomAccountName=" + username + ")";
SearchResult adSearchResult = adSearch.FindOne();
UserID = username;
UserName = StripLoggedUserName(adSearchResult.Path);
}
}
下一步,您可以使用以下代码将AD密码重置为:
As the next step, you can use the below code to reset AD password as:
public string ResetPassword(bool reset)
{
string sPwd = _user.Properties["sAMAccountName"][0].ToString() + ".tmp"; //static password here
int flags;
if(reset)
{
//first have to remove "Password Never Expires Flag"
flags = (int)_user.Properties["userAccountControl"].Value;
if(Convert.ToBoolean(flags & UF_DONT_EXPIRE_PASSWD))
{
flags = (flags ^ UF_DONT_EXPIRE_PASSWD);
_user.Properties["userAccountControl"].Value = flags;
}
if(_user.Properties.Contains("pwdLastSet"))
_user.Properties["pwdLastSet"].Value = 0;
else
_user.Properties["pwdLastSet"].Add(0);
}
else
{
//clear the change password at next login if it is there
if(_user.Properties.Contains("pwdLastSet"))
_user.Properties["pwdLastSet"].Value = -1;
else
_user.Properties["pwdLastSet"].Add(-1);
//set the password never expires flag.
flags = (int)_user.Properties["userAccountControl"].Value;
if(!Convert.ToBoolean(flags & UF_DONT_EXPIRE_PASSWD))
{
flags = (flags | UF_DONT_EXPIRE_PASSWD);
_user.Properties["userAccountControl"].Value = flags;
}
}
//Change thread context to Admin's **IMPERSONATION CODE STARTS HERE**
IntPtr token = IntPtr.Zero;
string username = ""; //same as in your _user constructor
string domain = ""; //same as in your _user constructor
bool result = LogonUser(username, domain , Config.Settings.AdminPassword, 3, 0, out token);
if(!result)
{
int errCode = GetLastError();
string errMessage = String.Empty;
switch(errCode)
{
case 5:
errMessage = "Access Denied";
break;
case 1326:
errMessage = "Logon failure: unknown user name or bad password.";
break;
}
throw new Exception(String.Format("GetLastError() returned {0}, \"{1}\"", errCode, errMessage));
}
else
{
WindowsIdentity wi = new WindowsIdentity(token);
WindowsImpersonationContext wic = wi.Impersonate();
_user.Invoke("SetPassword", new object[]{sPwd.ToLower()});
_user.CommitChanges();
wic.Undo(); //end impersonation **END IMPERSONATION**
CloseHandle(token);
}
return sPwd.ToLower();
}
您可以尝试以下PowerShell命令:
You can try this PowerShell command: