确定任意计算机是否已加入Active Directory域

本文关键字:Active Directory 任意 计算机 是否 | 更新日期: 2023-09-27 18:25:22

我想查询Active Directory,看看是否只使用机器名加入任意机器(即不仅仅是我的代码运行的本地机器)

我知道System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain(),但这只是告诉我本地机器是否是域的成员。

在我的情况下,我有一个机器名称列表,我想确定哪些机器名称已加入,哪些未加入。有办法做到这一点吗?

可能的方法

以下是使用System.DirectoryServices.AccountManagement的可能答案。如果AD中没有具有匹配机器名称的计算机,则将返回null值。然而,这种方法并不理想,因为它需要管理凭据:

const string S_USER = "username";
const string S_PASS = "password";
static public ComputerPrincipal GetComputerInfo(string ComputerName)
{
    try
    {
        // enter AD settings  
        PrincipalContext AD = new PrincipalContext(ContextType.Domain, 
            DOMAIN, S_USER, S_PASS);
        // create search user and add criteria
        ComputerPrincipal c = new ComputerPrincipal(AD);
        c.Name = ComputerName;
        // search for user  
        PrincipalSearcher search = new PrincipalSearcher(c);
        ComputerPrincipal result = (ComputerPrincipal)search.FindOne();
        search.Dispose();
        return result;
    }
    catch (Exception e)
    {
        Console.WriteLine("Error: " + e.Message);
    }
    Console.Read();
    return null;
}

是否有一种不需要管理证书的替代方法?

确定任意计算机是否已加入Active Directory域

这将是通过其NETBIOS域确定它的一种方法:

[DllImport("netapi32.dll", CharSet = CharSet.Auto)]
    static extern int NetWkstaGetInfo(string server,
        int level,
        out IntPtr info);
[DllImport("netapi32.dll", CharSet = CharSet.Auto)]
    static extern int NetWkstaGetInfo(string server,
        int level,
        out IntPtr info);
    [DllImport("netapi32.dll")]
    static extern int NetApiBufferFree(IntPtr pBuf);
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    class WKSTA_INFO_100
    {
        public int wki100_platform_id;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string wki100_computername;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string wki100_langroup;
        public int wki100_ver_major;
        public int wki100_ver_minor;
    }
    public static string GetMachineNetBiosDomain(string server)
    {
        IntPtr pBuffer = IntPtr.Zero;
        WKSTA_INFO_100 info;
        int retval = NetWkstaGetInfo(server, 100, out pBuffer);
        if (retval != 0)
            throw new Win32Exception(retval);
        info = (WKSTA_INFO_100)Marshal.PtrToStructure(pBuffer, typeof(WKSTA_INFO_100));
        string domainName = info.wki100_langroup;
        NetApiBufferFree(pBuffer);
        return domainName;
    }