如何檢測機器是否加入Active Directory域(與工作組模式相比)?如何檢測機器是否加入域(在C#中)?
回答
你可以的PInvoke到Win32 API中的諸如NetGetDcName這將返回一個空/空字符串的非加入域的機器。
更好的是NetGetJoinInformation它會明確告訴你機器是否在工作組或域中未被連接。
使用NetGetJoinInformation
我放在一起這一點,這爲我工作:
public class Test
{
public static bool IsInDomain()
{
Win32.NetJoinStatus status = Win32.NetJoinStatus.NetSetupUnknownStatus;
IntPtr pDomain = IntPtr.Zero;
int result = Win32.NetGetJoinInformation(null, out pDomain, out status);
if (pDomain != IntPtr.Zero)
{
Win32.NetApiBufferFree(pDomain);
}
if (result == Win32.ErrorSuccess)
{
return status == Win32.NetJoinStatus.NetSetupDomainName;
}
else
{
throw new Exception("Domain Info Get Failed", new Win32Exception());
}
}
}
internal class Win32
{
public const int ErrorSuccess = 0;
[DllImport("Netapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern int NetGetJoinInformation(string server, out IntPtr domain, out NetJoinStatus status);
[DllImport("Netapi32.dll")]
public static extern int NetApiBufferFree(IntPtr Buffer);
public enum NetJoinStatus
{
NetSetupUnknownStatus = 0,
NetSetupUnjoined,
NetSetupWorkgroupName,
NetSetupDomainName
}
}
ManagementObject cs;
using(cs = new ManagementObject("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'"))
{
cs.Get();
Console.WriteLine("{0}",cs["domain"].ToString());
}
這應該讓你獲得域名。我相信如果你是工作組的一部分而不是域,它將是空的或空的。
確保引用System.Management
的環境變量可以爲你工作。
Environment.UserDomainName
MSDN Link瞭解更多詳情。
Environment.GetEnvironmentVariable("USERDNSDOMAIN")
我不確定此環境變量是否存在,而不在域中。
糾正我,如果我錯了的Windows管理員怪才 - 我相信電腦可以在幾個領域,因此它可能是更重要的是要知道你是不是它任何是什麼域,如果有的話,域。
如果您不必這樣做,就別傻瓜了。
參考的System.DirectoryServices,然後調用:
System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain()
拋出ActiveDirectoryObjectNotFoundException
如果機器未加入域。 返回的域對象包含您正在查找的Name屬性。
只是想砸搶的代碼在VB:
Public Class Test
Public Function IsInDomain() As Boolean
Try
Dim status As Win32.NetJoinStatus = Win32.NetJoinStatus.NetSetupUnknownStatus
Dim pDomain As IntPtr = IntPtr.Zero
Dim result As Integer = Win32.NetGetJoinInformation(Nothing, pDomain, status)
If (pDomain <> IntPtr.Zero) Then
Win32.NetApiBufferFree(pDomain)
End If
If (result = Win32.ErrorSuccess) Then
If (status = Win32.NetJoinStatus.NetSetupDomainName) Then
Return True
Else
Return False
End If
Else
Throw New Exception("Domain Info Get Failed")
End If
Catch ex As Exception
Return False
End Try
End Function
End Class
Public Class Win32
Public Const ErrorSuccess As Integer = 0
Declare Auto Function NetGetJoinInformation Lib "Netapi32.dll" (ByVal server As String, ByRef IntPtr As IntPtr, ByRef status As NetJoinStatus) As Integer
Declare Auto Function NetApiBufferFree Lib "Netapi32.dll" (ByVal Buffer As IntPtr) As Integer
Public Enum NetJoinStatus
NetSetupUnknownStatus = 0
NetSetupUnjoined
NetSetupWorkgroupName
NetSetupDomainName
End Enum
End Class
以及史蒂芬代碼在這裏:
Dim cs As System.Management.ManagementObject
Try
cs = New System.Management.ManagementObject("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")
cs.Get()
dim myDomain as string = = cs("domain").ToString
Catch ex As Exception
End Try
我認爲,只有第二個代碼將讓你知道什麼即使當前用戶不是域成員,域也會加入該域。
這裏是我基於本文中的幾個答案開發的異常處理/註釋方法。
- 獲取您計算機連接到的域。
僅當用戶實際登錄到域帳戶時才返回域名。
/// <summary> /// Returns the domain of the logged in user. /// Therefore, if computer is joined to a domain but user is logged in on local account. String.Empty will be returned. /// Relavant StackOverflow Post: http://stackoverflow.com/questions/926227/how-to-detect-if-machine-is-joined-to-domain-in-c /// </summary> /// <seealso cref="GetComputerDomainName"/> /// <returns>Domain name if user is connected to a domain, String.Empty if not.</returns> static string GetUserDomainName() { string domain = String.Empty; try { domain = Environment.UserDomainName; string machineName = Environment.MachineName; if (machineName.Equals(domain,StringComparison.OrdinalIgnoreCase)) { domain = String.Empty; } } catch { // Handle exception if desired, otherwise returns null } return domain; } /// <summary> /// Returns the Domain which the computer is joined to. Note: if user is logged in as local account the domain of computer is still returned! /// </summary> /// <seealso cref="GetUserDomainName"/> /// <returns>A string with the domain name if it's joined. String.Empty if it isn't.</returns> static string GetComputerDomainName() { string domain = String.Empty; try { domain = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name; } catch { // Handle exception here if desired. } return domain; }
您可能需要使用DomainRole兩個WMI領域嘗試。 0和2的值分別顯示獨立工作站和獨立服務器。
我們正在使用此爲夏配置我們的網絡審計軟件,所以我在那兒剽竊此方法...
/// <summary>
/// Determines whether the local machine is a member of a domain.
/// </summary>
/// <returns>A boolean value that indicated whether the local machine is a member of a domain.</returns>
/// <remarks>http://msdn.microsoft.com/en-gb/library/windows/desktop/aa394102(v=vs.85).aspx</remarks>
public bool IsDomainMember()
{
ManagementObject ComputerSystem;
using (ComputerSystem = new ManagementObject(String.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName)))
{
ComputerSystem.Get();
UInt16 DomainRole = (UInt16)ComputerSystem["DomainRole"];
return (DomainRole != 0 & DomainRole != 2);
}
}
您可以檢查的Win32_ComputerSystem WMI類的PartOfDomain財產。 的MSDN說:
PartOfDomain
數據類型:布爾
訪問類型:只讀
如果真,計算機是域的一部分。如果該值爲NULL,則該計算機不在域中或狀態未知。如果 從域中脫離計算機,則該值將變爲false。
/// <summary>
/// Determines whether the local machine is a member of a domain.
/// </summary>
/// <returns>A boolean value that indicated whether the local machine is a member of a domain.</returns>
/// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx</remarks>
public bool IsDomainMember()
{
ManagementObject ComputerSystem;
using (ComputerSystem = new ManagementObject(String.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName)))
{
ComputerSystem.Get();
object Result = ComputerSystem["PartOfDomain"];
return (Result != null && (bool)Result);
}
}
也可以通過使用system.net
string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName
如果域字符串是空的機器未綁定調用。
如果本地用戶登錄所提出的方案上述返回一個域的機器上假
最可靠的方法我已經發現的是通過WMI:
http://msdn.microsoft.com/en-us/library/aa394102(v=vs.85).aspx(見DomainRole兩個)
如果性能問題,使用GetComputerNameEx功能:
bool IsComputerInDomain()
{
uint domainNameCapacity = 512;
var domainName = new StringBuilder((int)domainNameCapacity);
GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsDomain, domainName, ref domainNameCapacity);
return domainName.Length > 0;
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool GetComputerNameEx(
COMPUTER_NAME_FORMAT NameType,
StringBuilder lpBuffer,
ref uint lpnSize);
enum COMPUTER_NAME_FORMAT
{
ComputerNameNetBIOS,
ComputerNameDnsHostname,
ComputerNameDnsDomain,
ComputerNameDnsFullyQualified,
ComputerNamePhysicalNetBIOS,
ComputerNamePhysicalDnsHostname,
ComputerNamePhysicalDnsDomain,
ComputerNamePhysicalDnsFullyQualified
}
您可以查看使用WMI:
private bool PartOfDomain()
{
ManagementObject manObject = new ManagementObject(string.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName));
return (bool)manObject["PartOfDomain"];
}
- 1. 如何檢測機器是否在線?
- 2. 如何檢測驅動器在C#中是否有回收站?
- 3. 如何檢測在C++中是否附有調試器?
- 4. 檢測計算機是否爲域控制器
- 5. 檢測顯示器是否在c#
- 6. 檢測耳機是否插入iPhone
- 7. 檢測耳機是否插入iPhone/iPod
- 8. 如何檢測Windows機器是否正在運行IPV4或IPV6?
- 9. 如何檢測用戶輸入是否爲域名?
- 10. 我的c#程序如何檢測它是否插入用戶主域?
- 11. 如何檢測Javascript是否在Opera的跨域IFrame中運行?
- 12. 我如何檢測我的局域網連接是否在C++中down/up
- 13. 如何檢查Windows機器加入的Azure AD域的名稱?
- 14. C#:如何檢測屏幕閱讀器是否正在運行?
- 15. C#如何檢測是否有'/'字符?
- 16. 如何檢測extern「C」是否生效
- 17. 如何檢查耳機是否插入?
- 18. 如何檢測Galaxy S是否插入電視機?
- 19. 如何檢測類是否可注入
- 20. 如何判斷一臺計算機是否加入域?
- 21. 檢測www子域是否存在
- 22. 如何檢測瀏覽器是否正在加載
- 23. 如何檢測瀏覽器是否正在加載新頁面
- 24. 如何檢查用戶是否在C#中的域管理員
- 25. 如何檢測iframe是否已加載?
- 26. 如何檢測服務器是否關機?
- 27. 如何檢測機器人
- 28. JS:如何檢測光標是否在文本域
- 29. Pygame - 如何檢測sprite是否在區域?
- 30. c#檢查域是否存在
如果不在域中,它將返回「WORKGROUP」。這將起作用(除非你在名爲「WORKGROUP」的域中!),但在選擇它作爲正確答案之前,我會稍等一下,看看是否有非基於WMI的方法。 – DSO 2009-05-29 14:38:04
謝謝你讓我知道。我只有我的工作機器進行測試,並且無法將其完全從域中刪除以進行測試。 – Stephan 2009-05-29 14:41:24
第二個想法我不認爲這會奏效。事實證明,我的測試框的工作組名稱實際上是WORKGROUP。我認爲它返回工作組名稱,而不是一個固定的值,從API的角度來看這更有意義,但它意味着你不能用它來確定它的域是否加入。 – DSO 2009-05-29 16:31:00