Как найти адрес контроллера домена

DNS and DHCP are the best way to check since there can be Unix/Linux machines on the network managed by the AD domain controller or acting as the domain controller.

Plus, considering active directory is nothing more than Microsoft’s version of Kerberos, LDAP, dhcp and dns. It would be better to understand and debug things at lower layers than layer 7+. This is because the operating system would preform these same requests and the underlining RFC for each protocol actually operates at a OSI level not the “insert favorite tool here” level.

One can go a step further and query the dhcp for options 6, 15, and 44 to get the domain name, domain name server, and Wins/NetBIOS name server.

Then using dns to check for the _kerberos._tcp, _kpasswd._tcp, _LDAP._TCP.dc._msdcs, and _ldap._tcp SRV records:

nslookup -type=srv _kerberos._tcp.EXMAPLE.COM
nslookup -type=srv _kpasswd._tcp.EXAMPLE.COM
nslookup -type=srv _ldap._tcp.EXAMPLE.COM
nslookup -type=srv _ldap._tcp.dc._msdcs.EXAMPLE.COM

.EXAMPLE.COM ::= value returned from dhcp option-1

This breaks down into three areas, two are protocol supported DNS-SD records:

  • _kerberos._tcp and _kpasswd._tcp (also under UNIX/Linux/OSX+some windows networks has _kadmin._tcp) are for kerberos
  • _ldap._tcp is for ldap (openldap, opendc, sun/oracle directory, ms ad)
    _LDAP._TCP.dc._msdcs is the Microsoft only extension to ldap to map the domain controller.

Windows Domain Controller (DC) is a server that responds to security authentication requests within a Windows Domain (group of networked computers controlled by domain controller).

In this short note i will show how to find out which DC a computer is authenticated to using Windows CMD and PowerShell.

Cool Tip: Check if the computer is in a domain! Read more →

Get domain controller name in Windows CMD:

C:> echo %LogOnServer%

Get domain controller name in PowerShell:

PS C:> $env:LogOnServer

To find out the FQDN and IP address of the domain controller, you can use nslookup command that works both in Windows CMD and PowerShell:

C:> nslookup MYDOMAINCONTROLLER01

Cool Tip: How to determine whether the current user is a Domain User account or a Local User account! Read more →

Was it useful? Share this post with the world!

I am looking for a way to determine what the Name/IP Address of the domain controller is for a given domain that a client computer is connected to.

At our company we have a lot of small little networks that we use for testing and most of them have their own little domains. As an example, one of the domains is named “TESTLAB”. I have an Windows XP workstation that is a member of the TESTLAB domain and I am trying to figure out the name of the domain controller so that I can go and look to see what users have been defined for the domain. In our lab there is a mix of Windows Server 2000 and Windows Server 2003 (and in reality probably a couple of NT 4 Servers) so it would be nice to find a solution that would work for both.

Looking on the Internet, it looks like there are various utilities, such as Windows Power Shell or nltest, but these all require that you download and install other utilities. I was hoping to find a way to find the domain controller without having to install anything additional.

EDIT If I wanted to write a program to find the domain controller or the users in the current domain, how would I go about doing that?

George Stocker's user avatar

asked Dec 9, 2008 at 20:03

Dorky Engineer's user avatar

Dorky EngineerDorky Engineer

1,0542 gold badges7 silver badges9 bronze badges

1

With the most simple programming language: DOS batch

echo %LOGONSERVER%

answered Dec 9, 2008 at 20:55

MZywitza's user avatar

3

In cmd on Windows, type the following commande:

nltest /dclist:{domainname}

It lists all domain controllers in particular domain

Luca Detomi's user avatar

Luca Detomi

5,5347 gold badges52 silver badges76 bronze badges

answered Oct 1, 2015 at 10:16

Lado Morela's user avatar

Lado MorelaLado Morela

2012 silver badges2 bronze badges

1

In C#/.NET 3.5 you could write a little program to do:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    string controller = context.ConnectedServer;
    Console.WriteLine( "Domain Controller:" + controller );
} 

This will list all the users in the current domain:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    using (UserPrincipal searchPrincipal = new UserPrincipal(context))
    {
       using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
       {
           foreach (UserPrincipal principal in searcher.FindAll())
           {
               Console.WriteLine( principal.SamAccountName);
           }
       }
    }
}

answered Dec 9, 2008 at 20:30

tvanfosson's user avatar

tvanfossontvanfosson

522k99 gold badges697 silver badges794 bronze badges

0

From command line query the logonserver env variable.

C:> SET L

LOGONSERVER=”DCNAME

answered Feb 23, 2015 at 21:55

Sri's user avatar

SriSri

1011 silver badge2 bronze badges

0

Run gpresult at a Windows command prompt. You’ll get an abundance of information about the current domain, current user, user & computer security groups, group policy names, Active Directory Distinguished Name, and so on.

answered Jan 4, 2013 at 2:46

ErikE's user avatar

ErikEErikE

48.5k23 gold badges148 silver badges195 bronze badges

4

in Powershell: $env:logonserver

evandrix's user avatar

evandrix

6,0114 gold badges27 silver badges38 bronze badges

answered Mar 6, 2018 at 9:30

Wim's user avatar

WimWim

611 silver badge1 bronze badge

0

To retrieve the information when the DomainController exists in a Domain in which your machine doesn’t belong, you need something more.

  DirectoryContext domainContext =  new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword");

  var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);
  var controller = domain.FindDomainController();

answered Nov 13, 2012 at 13:30

Brett Veenstra's user avatar

Brett VeenstraBrett Veenstra

47.6k18 gold badges69 silver badges86 bronze badges

Находим контроллер домена в сети.

Для того чтобы узнать IP-адреса и имена контроллеров домена в сети нужно в командной строке ввести следующий командлет:

nslookup

Как найти контроллер домена в сети

Информация о материале
Автор: Максим Донецкий
Категория: Администрирование компьютерной сети

Опубликовано: 08 августа 2016

  • Системное администрирование

  • Windows

  • Active Directory

Комментарии   


0


#2
Имя
12.03.2021 13:45

Если комп уже в домене, то можно и так. А если нужно зайти по РДП на КД с не-доменного компа? Например, чтобы посмотреть крайнее использованное имя и назначить следующее.


Цитировать


+5


#1
Ivan
01.11.2017 14:14

Неверно.
Так мы узнаем DNS сервер по умолчанию, но он не обязательно совпадает с контроллером домена.

Нужно так
> set logon
В ответе получим имя сервера, на котором мы залогинились.


Цитировать

Командлет Get-ADDomainController можно использовать для получения информации о контроллерах домена в Active Directory. Данный командлет входит в состав модуля Active Directory для PowerShell и требует установки отдельного компонента RSAT (в Windows 10 1809 и выше RSAT устанавливается по-новому).

Содержание:

  • Командлет Get-ADDomainController
  • Используем Get-ADDomainController для выборки контроллеров домена по условиям
  • PowerShell скрипт проверки доступности всех контроллеров домена

Командлет Get-ADDomainController

При запуске
Get-ADDomainController
без параметров командлет выводит информацию о текущем контроллере домена (LogonServer), который используется данным компьютером для аутентификации (DC выбирается при загрузке в соответствии с топологией сайтов AD).

Get-ADDomainController информация о текущем контроллере домена

Командлет вернул все поля с информацией о контроллере домена, доступной в AD.

ComputerObjectDN : CN=mskDC01,OU=Domain Controllers,DC=corp,DC=winitpro,DC=ru DefaultPartition : DC=corp,DC=winitpro,DC=ru Domain : corp.winitpro.ru Enabled : True Forest : winitpro.ru HostName : mskDC01.corp.winitpro.ru InvocationId : 96234a-7fc6-4a32-9e62-3b32343ab4ad IPv4Address : 10.1.10.6 IPv6Address :  

IsGlobalCatalog : True IsReadOnly : False LdapPort : 389 Name : mskDC01 NTDSSettingsObjectDN : CN=NTDS Settings,CN=mskDC01,CN=Servers,CN=MskCenter,CN=Sites,CN=Configuration,DC=winitpro,DC =ru OperatingSystem : Windows Server 2008 R2 Standard OperatingSystemHotfix : OperatingSystemServicePack : Service Pack 1 OperatingSystemVersion : 6.1 (7601) OperationMasterRoles : {} Partitions : {DC=ForestDnsZones,DC=winitpro,DC=ru, DC=DomainDnsZones,DC=corp,DC=winitpro,DC=ru, CN=Schema,CN=Configuration,DC=winitpro,DC=ru...} ServerObjectDN : CN=mskDC01,CN=Servers,CN=MskCenter,CN=Sites,CN=Configuration,DC=winitpro,DC=ru ServerObjectGuid : 8052323-e294-4430-a326-9553234431d6 Site : MskCenter SslPort : 636

Также вы можете найти контроллер домена, к которому должен относится ваш компьютер через механизм DCLocator:

Get-ADDomainController –Discover

Вы можете найти ближайший доступный DC с активной ролью AD Web Services:

Get-ADDomainController –ForceDiscover -Discover -Service ADWS

Параметр Service можно использовать, чтобы найти PDC в домене:

Get-ADDomainController -Discover -Service PrimaryDC

Если ваш контроллер домена не найден или не отвечает, вы можете найти контроллер домена в ближайшем сайте AD (определяется по весу межсайтовых связей):

Get-ADDomainController –Discover –ForceDiscover -NextClosestSite

Чтобы вывести список все контроллеров домена в текущем домене, выполните:

Get-ADDomainController -Filter * | ft

Get-ADDomainController list

Посчитать количество контроллеров домена в AD можно с помощью команды:

Get-ADDomainController -Filter * | Measure-Object

кол-во контроллеров домена в ad

Выведем более удобную таблицу, в которой указаны все контроллеры домена с их именем, IP адресом, версией ОС и именем сайта AD:

Get-ADDomainController -Filter *| Select Name, ipv4Address, OperatingSystem, site | Sort-Object name

получить список DC с IP адресами и именами

Если вам нужно получить информацию о DC из другого домена, нужно указать имя любого доступного DC в стороннем домене с помощью параметра –Server (возможно при наличии доверительных отношений между доменами).

Get-ADDomainController -Filter * -server dc01.contoso.cpm | Select Name, ipv4Address, IsGlobalCatalog, Site

получить DC из стороннего домен

Используем Get-ADDomainController для выборки контроллеров домена по условиям

Рассмотрим несколько полезных командлетов, которые можно использовать для получения списка контролеров домена в AD по определенным критериям.

Найти контроллер домена по его IP адресу:

Get-ADDomainController -Identity "10.1.1.120"

Найти все DC, в имени которых есть символы DC04:

Get-ADDomainController -Filter { name -like "*dc04*"} | Select Name, ipv4Address, OperatingSystem, site

Поиск всех доступных DC в определенном сайте:

Get-ADDomainController -Discover -ForceDiscover -Site "Site-Name"

Вывести список DC в сайтах, имена которых начинаются с Mos*:

Get-ADDomainController -Filter {site -like "Mos*"} | Select Name, ipv4Address, OperatingSystem, site

Get-ADDomainController - получить список контроллеров домена в сайте AD

Вывести список всех Read Only контроллеров домена:

Get-ADDomainController -Filter { IsReadOnly -eq $true} | Select Name, ipv4Address, OperatingSystem, site

Найти DC в сайте “Site Name”, на которых включена роль Global Catalog:

Get-ADDomainController -Filter {site -eq "Site Name" -and IsGlobalCatalog -eq $true} | Select Name, ipv4Address, OperatingSystem, site

PowerShell скрипт проверки доступности всех контроллеров домена

Следующая конструкция позволяет перебрать все контроллеры домена в Active Directory и выполнить для каждого из них определенное действие:

$AllDCs = Get-ADDomainController -Filter *
ForEach($DC in $AllDCs)
{
do something
}

Ниже приведен пример простого PowerShell скрипта, который проверяет доступность LDAPS порта (TCP 636) на каждом DC в домене с помощью командлета Test-NetConnection. Если LDAPS порт на DC не доступен, появляется предупреждение.

$AllDCs = Get-ADDomainController -Filter * | Select-Object Hostname,Ipv4address,isGlobalCatalog,Site,Forest,OperatingSystem
ForEach($DC in $AllDCs)
{
$PortResult=Test-NetConnection -ComputerName $DC.Hostname -Port 636 -InformationLevel Quiet
if ($PortResult -ne "$True"){
write-host $DC.Hostname " не доступен" -BackgroundColor Red -ForegroundColor White
}else {
write-host $DC.Hostname " доступен" }
}

скрипт проверки доступности всех DC в домене

Получился простой скрипт мониторинга доступности DC. Ест еще различные сценарии перебора всех DC в домене. В предыдущих статьях мы уже показывали, как использовать Get-ADDomainController для поиска определенного события в журналах на всех контролерах домена. Например, для: поиска события блокировки учетной записи пользователя, поиска событий NTLMv1 аутентификации, поиска событий добавления пользователя в группу AD и т.д.

Добавить комментарий