获取所有计算机的列表,以及它是否已登录到 AD

本文关键字:是否 登录 AD 计算机 列表 获取 | 更新日期: 2023-09-27 18:33:59

我正在尝试接收AD中的所有计算机以及当前登录的计算机。我尝试通过检查"lastLogonStamp"来执行此操作,但这返回了错误的值,说我的服务器在八天前登录到 AD。即使我重新启动服务器,它也说同样的话。我从这里的另一个问题中获得了代码:

如何列出所有计算机以及它们上次在AD中登录的时间?

public DataTable GetListOfComputers(string domain, string userName, string password)
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain,
                userName, password, AuthenticationTypes.Secure);
        DirectorySearcher search = new DirectorySearcher(entry);
        string query = "(objectclass=computer)";
        search.Filter = query;
        search.PropertiesToLoad.Add("name");
        search.PropertiesToLoad.Add("lastLogonTimestamp");
        SearchResultCollection mySearchResultColl = search.FindAll();
        DataTable results = new DataTable();
        results.Columns.Add("name");
        results.Columns.Add("lastLogonTimestamp");
        foreach (SearchResult sr in mySearchResultColl)
        {
            DataRow dr = results.NewRow();
            DirectoryEntry de = sr.GetDirectoryEntry();
            dr["name"] = de.Properties["Name"].Value;
            dr["lastLogonTimestamp"] = DateTime.FromFileTimeUtc(long.Parse(sr.Properties["lastLogonTimestamp"][0].ToString()));
            results.Rows.Add(dr);
            de.Close();
        }
        return results;
    }

获取所有计算机的列表,以及它是否已登录到 AD

如果使用的是 .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 
ComputerPrincipal qbeComputer = new ComputerPrincipal(ctx);
// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeComputer);
// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
    ComputerPrincipal cp = found as ComputerPrincipal;
    if(cp != null)
    {
       string computerName = cp.Name;
       DateTime lastLogon = cp.LastLogon;
    }
}

如果您还没有 - 请务必阅读 MSDN 文章在 .NET Framework 3.5 中管理目录安全主体,该文章很好地展示了如何充分利用 System.DirectoryServices.AccountManagement 中的新功能。或者参阅 System.DirectoryServices.AccountManagement 命名空间上的 MSDN 文档。