AD搜索和属性以及字典使用
本文关键字:字典 搜索 属性 AD | 更新日期: 2023-09-27 18:16:30
为了确定计算机帐户是否孤立,我想查询所有可信域的所有域控制器,以检索所有计算机的lastLogon和lastLogonTimeStamp。我有一个程序可以工作(至少在我的测试环境中),但是我有几个问题,我希望你能回答。
-
我使用的方法是找到域和域控制器,然后检索AD信息,尽可能使用最少的资源(网络/域控制器CPU和RAM) ?如何改进它们?
-
是否可能在字典键/值对中有超过1个值?为LastLogIn使用一个字典,而为LastLogInTimestamp使用另一个字典,这似乎是一种浪费。
-
参考字典和AD属性:我如何检查不存在的值,而不是使用Try/Catch?
试{//这个DC是否比上一个DC电流大?if (dict_LastLogIn[pc] <(长)result.Properties["lastlogon"][0]){dict_LastLogIn[pc] = (long)result.Properties["lastlogon"][0];}}抓{//项目还不存在…试一试{dict_LastLogIn[pc] = (long)result.Properties["lastlogon"][0];}抓{//…或//没有LastLogin…dict_LastLogIn[pc] = 0;}}
完整代码如下:
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
namespace dictionary
{
class Program
{
internal static Dictionary<string, long> dict_LastLogIn =
new Dictionary<string, long>();
internal static Dictionary<string, long> dict_LastLogInTimeStamp =
new Dictionary<string, long>();
internal static Dictionary<string, DateTime> output =
new Dictionary<string, DateTime>();
internal static bool AreAllDCsResponding = true;
static void Main(string[] args)
{
Console.BufferWidth = 150;
Console.BufferHeight = 9999;
Console.WindowWidth = 150;
Dictionary<String, int> dict_domainList = new Dictionary<String, int>();
Dictionary<String, int> dict_dcList = new Dictionary<String, int>();
//Get the current domain's trusts.
Domain currentDomain = Domain.GetCurrentDomain();
Console.WriteLine("Retrieved the current Domain as {0}", currentDomain.ToString());
var domainTrusts = currentDomain.GetAllTrustRelationships();
Console.WriteLine(" {0} trusts were found.", domainTrusts.Count);
//Add the current domain to the dictonary. It won't be in domainTrusts!
dict_domainList.Add(currentDomain.ToString(), 0);
// Then add the other domains to the dictonary...
foreach (TrustRelationshipInformation trust in domainTrusts)
{
dict_domainList.Add(trust.TargetName.Substring(0, trust.TargetName.IndexOf(".")).ToUpper(), 0);
Console.WriteLine(" Adding {0} to the list of trusts.", trust.TargetName.Substring(0, trust.TargetName.IndexOf(".")).ToUpper());
}
// Now get all DCs per domain
foreach (var pair in dict_domainList)
{
DirectoryContext dc = new DirectoryContext(DirectoryContextType.Domain, pair.Key);
Domain _Domain = Domain.GetDomain(dc);
foreach (DomainController Server in _Domain.DomainControllers)
{
dict_dcList.Add(Server.Name, 0);
Console.WriteLine(" Adding {0} to the list of DCs.", Server.Name.ToUpper());
}
// Now search through every DC
foreach (var _pair in dict_dcList)
{
Console.WriteLine(" Querying {0} for Computer objects.", _pair.Key.ToUpper());
Search(pair.Key);
Console.WriteLine("'n");
Console.WriteLine("The following Computer objects were found:");
}
if (AreAllDCsResponding == true)
{
ConvertTimeStamp(dict_LastLogIn);
}
else
{
ConvertTimeStamp(dict_LastLogInTimeStamp);
}
Console.ReadLine();
}
}
internal static void Search(string domainName)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domainName);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(&(ObjectCategory=computer))");//(lastlogon=*)(lastlogonTimeStamp=*))");
mySearcher.SizeLimit = int.MaxValue;
mySearcher.PropertiesToLoad.Add("DistinguishedName");
mySearcher.PropertiesToLoad.Add("lastlogon");
mySearcher.PropertiesToLoad.Add("lastlogonTimeStamp");
try
{
foreach (System.DirectoryServices.SearchResult result in mySearcher.FindAll())
{
string pc = result.Properties["DistinguishedName"][0].ToString();
try
{ // Is this DC more current than the last?
if (dict_LastLogIn[pc] < (long)result.Properties["lastlogon"][0])
{
dict_LastLogIn[pc] = (long)result.Properties["lastlogon"][0];
}
}
catch
{ // The item doesn't exist yet..
try
{
dict_LastLogIn[pc] = (long)result.Properties["lastlogon"][0];
}
catch
{ // .. or
// There is no last LastLogin...
dict_LastLogIn[pc] = 0;
}
}
try
{
// Not yet replicated?...
if (dict_LastLogInTimeStamp[pc] < (long)result.Properties["lastlogonTimeStamp"][0])
{
dict_LastLogInTimeStamp[pc] = (long)result.Properties["lastlogonTimeStamp"][0];
}
}
catch
{ // The item doesn't exist yet..
try
{
dict_LastLogInTimeStamp[pc] = (long)result.Properties["lastlogonTimeStamp"][0];
}
catch
{ // .. or
// There is no last LastLoginTimeStamp...
dict_LastLogInTimeStamp[pc] = 0;
}
}
}
}
catch (System.Runtime.InteropServices.COMException)
{
//If even one DC doesn't answer, don't use LastLogon!
//Use the less accurate, but replicated(!) LastLogonTimeStamp.
AreAllDCsResponding = false;
}
}
internal static void ConvertTimeStamp(Dictionary<string, long> _dict)
{
foreach (var pair in _dict)
{
output.Add(pair.Key, DateTime.FromFileTime(pair.Value));
Console.WriteLine("{0} - {1}", pair.Key, DateTime.FromFileTime(pair.Value));
}
}
}
}
谢谢你提供的任何帮助。
在高层次上,我不确定您的最终游戏是什么,但是,您确定您真的想要查询每个DC的lastLogon吗?这可能会很贵。还有,你为什么要走信任链?你确定你不只是想要所有的域在一个给定的森林(Forest.Domains
)?
回答你的问题:
-
这看起来不错,但你应该做几件事:
- 将过滤器调整为
(&(objectCategory=computer)(objectClass=computer))
- 添加
mySearcher.PageSize = 1000
- 移除
mySearcher.SizeLimit = int.MaxValue
- 将过滤器调整为
-
您可以使用
Tuple
- http://msdn.microsoft.com/en-us/library/system.tuple(VS.90).aspx。或者直接定义一个自定义类作为值,然后声明Dictionary为Dictionary:公共类LogonTimeStamps{
public long LastLogon {get;设置;}
public long LastLogonTimeStamp {get;设置;}
}
-
对于Dictionary,使用
myDictionary.ContainsKey(yourKey)
。对于AD,您应该能够使用result.Properties.Contains("yourAttribute")
.