[英]Find all locked users in AD using c#
下面列出的代碼對我來說很好但是我想要一個鎖定而不是指定特定用戶的所有用戶的列表,可以幫助我拓寬這個代碼的范圍
using (var context = new PrincipalContext( ContextType.Domain ))
{
using (var user = UserPrincipal.FindByIdentity( context,
IdentityType.SamAccountName,
name ))
{
if (user.IsAccountLockedOut())
{
... your code here...
}
}
}
上面列出的代碼對我來說很好,但我希望鎖定所有用戶的列表,而不是指定特定用戶。
這是最終工作 - 感謝所有貢獻者。
當用戶被鎖定時,他們不會在他們登錄之前進入“未鎖定”(當在ldap搜索中引用lockedout子句時); 所以...使用鎖定的qry為您提供一個廣泛的鎖定用戶列表,然后您可以使用isaccountlockedout()方法縮小范圍。 問候!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
namespace ConsoleApplication5
{
class Lockout : IDisposable
{
DirectoryContext context;
DirectoryEntry root;
public Lockout()
{
string domainName = "domain.com";
this.context = new DirectoryContext(
DirectoryContextType.Domain,
domainName
);
//get our current domain policy
Domain domain = Domain.GetDomain(this.context);
this.root = domain.GetDirectoryEntry();
}
public void FindLockedAccounts()
{
string qry = " (&(&(&(objectCategory=person)(objectClass=user)(lockoutTime:1.2.840.113556.1.4.804:=4294967295)(!UserAccountControl:1.2.840.113556.1.4.803:=2)(!userAccountControl:1.2.840.113556.1.4.803:=65536)))) ";
DirectorySearcher ds = new DirectorySearcher(
this.root,
qry
);
using (SearchResultCollection src = ds.FindAll())
{
foreach (SearchResult sr in src)
{
using (var context = new PrincipalContext( ContextType.Domain ))
{
string name = sr.Properties["SamAccountName"][0].ToString();
using (var user = UserPrincipal.FindByIdentity( context,
IdentityType.SamAccountName,
name ))
{
if (user.IsAccountLockedOut())
{
Console.WriteLine("{0} is locked out", sr.Properties["name"][0]);
}
}
}
}
}
}
public void Dispose()
{
if (this.root != null)
{
this.root.Dispose();
}
}
}
}
編輯:誤讀問題。 更新的答案
現在就試試
為什么不呢:
var lockedUsers = new List<UserPrincipal>();
using (var context = new PrincipalContext(ContextType.Domain))
{
GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Users");
foreach (var userPrincipal in grp.GetMembers(false))
{
var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userPrincipal.UserPrincipalName);
if (user != null)
{
if (user.IsAccountLockedOut())
{
lockedUsers.Add(user);
}
}
}
}
//Deal with list here
您可以使用lockoutTime
屬性,但是,它不一定是微不足道的。 該屬性具有用戶被鎖定的時間。 因此,如果您的域具有單個鎖定策略,則可以搜索lockoutTime
值大於或等於(UTC現在 - 鎖定持續時間)的所有人。
如果您通過細粒度密碼策略有多個鎖定策略,那么這不是那么容易,因為您需要基於每個用戶計算它。
如果您的域具有永久鎖定(例如,您必須請求解鎖帳戶),則可以搜索大於零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.