【问题标题】:Is it possible to find the local computer in AD without hardcoding its domain?是否可以在不对其域进行硬编码的情况下在 AD 中找到本地计算机?
【发布时间】:2011-11-29 16:50:07
【问题描述】:

我正在使用 C# 通过查询 Active Directory 来查找本地计算机的 objectGuid。为此,我目前使用DirectorySearcher,将(硬编码)路径作为搜索根传递给它,然后按计算机名称过滤:

string adRootPath = @"LDAP://OU=foo,DC=bar,DC=baz,DC=com";    
DirectoryEntry adRoot = new DirectoryEntry(adRootPath);

DirectorySearcher searcher = new DirectorySearcher(adRoot);
searcher.Filter = @"(&(objectCategory=Computer)(CN=" + Environment.MachineName + "))";

我不想硬编码搜索根,想知道是否有更好的方法。我曾想过只使用一个空的搜索根,但我担心计算机名称在不同域中可能并不总是唯一的。

有没有更好的办法?

【问题讨论】:

    标签: c# .net active-directory


    【解决方案1】:

    如果您使用的是 .NET 3.5 或更高版本,则可以使用 PrincipalSearcher 和“按示例查询”主体进行搜索:

    // create your domain context
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    
    // define a "query-by-example" principal - here, we search for a ComputerPrincipal 
    // and with the name of "MyPC"
    ComputerPrincipal cp = new ComputerPrincipal(ctx);
    cp.Name = "MyPC";
    
    // create your principal searcher passing in the QBE principal    
    PrincipalSearcher srch = new PrincipalSearcher(cp);
    
    // find all matches
    foreach(var found in srch.FindAll())
    {
        // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
    }
    

    如果您还没有 - 一定要阅读 MSDN 文章 Managing Directory Security Principals in the .NET Framework 3.5,它很好地展示了如何充分利用 System.DirectoryServices.AccountManagement 中的新功能

    【讨论】:

    • 谢谢。是否保证 FindAll() 只找到一个结果(即本地计算机),即使不同 OU 之间存在重复的计算机名称?
    • @Eric: 不,FindAll() 将找到符合指定条件的 所有 次出现(顾名思义)。然后您可以检查例如ComputerPrincipal 上的 DistinguishedName 属性以查看计算机所在的 AD 树中的哪个位置。还有一个 .FindOne() 方法返回第一个匹配项 - 但您可能不知道还有其他计算机符合您的条件。
    • 啊,我明白了。好吧,我实际上只是想找到本地计算机的AD信息。似乎使用这种方法,我无法在结果中区分哪台计算机是本地计算机。
    • @Eric:我不确定——我不是网络管理员——但我有一种预感,计算机也需要在域中具有“唯一”名称——就像每个用户和组的“samAccountName”在所有 OU 中必须是唯一的。另外:你为什么不测试这个?尝试分配cp.Name = Environment.MachineName 并让代码运行并执行FindAll() - 它是否发现不止一台计算机??
    • 我在另一个问题上问过这个问题(测试只会告诉我我自己的计算机是否有重复,但我需要更广泛地了解),是的,计算机名称在域中是唯一的。
    【解决方案2】:

    您应该可以通过调用 RootDse 来获取域。

    这个网站有一个很好的例子 - Site with an example of RootDSE

    【讨论】:

      猜你喜欢
      • 2012-04-15
      • 2023-03-04
      • 2017-01-05
      • 1970-01-01
      • 2019-01-16
      • 2021-09-12
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多