1

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

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

就我而言,我有一个机器名称列表,我想确定哪些已加入,哪些未加入。有没有办法做到这一点?

可能的方法

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

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;
}

是否有不需要管理凭据的替代方法?

4

1 回答 1

0

这将是一种通过其 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;
    }
于 2013-07-30T04:37:15.917 回答