我想查询Active Directory以查看是否仅使用计算机名称 <加入任意计算机(即,不仅仅是运行我的代码的本地计算机) / p>
我知道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;
}
是否有其他方法不需要管理凭据?
答案 0 :(得分: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;
}