Как в dhcp найти mac адрес

Обновлено 09.09.2022

Поиск mac-адреса на DHCP с помощью PowerShell

Добрый день! Уважаемые читатели IT блога Pyatilistnik.org. В прошлый раз мы с вами разобрались, как подключаться по RDP протоколу, сравнили разный софт под эти задачи. В сегодняшней публикации мы снова побудем системными администраторами и попробуем найти нужный MAC-адрес на DHCP сервере используя PowerShell запросы. Я покажу в каких ситуациях вам это может потребоваться и что может дать. Давайте приступать.

Постановка задачи

Очень часто перед системным администратором стоит задача в вычислении устройства по разным вводным, чаще всего это определить, кто использует определенный IP. Например, на Cisco преобразование mac-адреса в IP это базовая вещь, но в крупных компаниях чаще всего отдел отвечающий за сеть и отдел серверного обслуживания разнесены, и у администраторов не всегда даже может быть доступ на данное оборудование.

Если DHCP сервер развернут на базе Windows Server, то администратор может сам проводить нужные запросы. Предположим, что у пользователя заблокировалась учетная запись Active Directory, в событиях вы видите  MAC-адрес, но не видите сразу IP. Сотрудник хэлпдеска придет к вам и попросит вас поискать нужное устройство, умея пользоваться PowerShell-ом вы легко с этим справитесь. Еще вы можете легко по части MAC-адреса посчитать, сколько устройств определенного вендора арендовало у вас адреса, так что навык полезный.

Как искать нужный MAC-адрес на DHCP сервере в PowerShell

В своем примере я буду искать mac-адреса для устройств HP Inc. Ранее я вам рассказывал, что вендоры оборудования уже давно между собой поделили диапазоны адресов. HP Inc имеет один из уникальных идентификаторов организации “f8:0d:ac“.

Уникальный идентификатор организации

Зная это, мы уже можем составлять запрос на PowerShell. Перейдите на сервер DHCP или на сервер, где установлен пакет RSAT с оснасткой DHCP, в противном случае при выполнении команды вы будите получать ошибку:

Get-DhcpServerv4Scope : The term ‘Get-DhcpServerv4Scope’ is not recognized as the name of a cmdlet, function, script fi
le, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.
At line:1 char:1
+ Get-DhcpServerv4Scope
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-DhcpServerv4Scope:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

'et-DhcpServerv4Scope is not recognized as the name of a cmdlet

Правильным действием будет сразу найти в DNS список серверов, которые выступают в роли DHCP серверов, для этого выполните в PowerShell:

Get-DhcpServerInDC

В моем примере их много, так что найдите нужные. Однако для дальнейшего использования в других командах вы можете сохранить имена возвращаемых серверов в переменной:

$dhcps = (Get-DhcpServerInDC).DnsName

Как следует из названия, командлет возвращает список авторизованных DHCP-серверов, зарегистрированных в Active Directory. Это означает, что вы не найдете мошеннических DHCP-серверов, которые были подключены к сети без ведома IT-отдела, а это классическая ситуация, что разработчик принес свой роутер, чтобы WIFI себе раздать. Далее обращаться можно используя $dhcps.

Get-DhcpServerv4Scope -ComputerName $dhcp

Вот простая конструкция для поиска всех MAC-адресов, где присутствует “f8:0d:ac“, запрос я делаю локально на DHCP сервере.

Get-DhcpServerv4Scope | Get-DhcpServerv4Lease | where {$_.ClientId -like “f8-0d-ac-**-**” } | FT -AutoSize

В результате я вижу информацию по всем областям аренды (Scope), что есть на DHCP сервере. Тут вы получите:

  • IP-адреса
  • ScopeId
  • ScopeId – Это и есть MAC-адреса
  • HostName – DNS имя устройства
  • AddressState – Состояние
  • LeaseExpiryTime – Время истечения аренды

конструкция для поиска всех MAC-адресов

Если делаете это с другого компьютера, то не забывайте в конструкцию указывать -ComputerName имя DHCP.

Get-DhcpServerv4Scope -ComputerName dhcp01 | Get-DhcpServerv4Lease -ComputerName dhcp01 | where {$_.ClientId -like “f8-0d-ac-**-**” } | FT -AutoSize

Чтобы найти конкретный MAC-адрес по всем областям, выполните:

Get-DhcpServerv4Scope | Get-DhcpServerv4Lease -EA SilentlyContinue -ClientId f8-0d-ac-23-2c-2f

Поиск физического адреса в DHCP через PowerShell

Еще вариантом скрипта, может выступать вот такая конструкция. Тут мы в явном виде задаем необходимые нам DHCP серверы в текстовом файле, подгружаем его и делаем запрос.

$StartTime = (Get-Date)
Start-Sleep -Seconds 10

# Импортируем список серверов из файла
$servers = Get-Content “c:Tempservers.txt”

#
foreach ($server in $servers)

{

Get-DhcpServerv4Scope | Get-DhcpServerv4Lease | where {$_.ClientId -like “f8-0d-ac-**-**” } | FT -AutoSize

}

$EndTime = (Get-Date)
$TotalTime = $EndTime-$StartTime
$TotalTime.ToString()

Чтобы посмотреть все области и арендованные IP выполните:

GetDhcpServerv4Scope | GetDhcpServerv4Lease или GetDhcpServerv4Scope -ComputerName dhcp01 | GetDhcpServerv4Lease -ComputerName dhcp01

На этом у меня все. Мы с вами разобрали, как искать нужные MAC-адреса на DHCP сервере, тем самым определяя, что за компьютер стоит за ним. С вами был Иван Сёмин, автор и создатель IT портала Pyatilistnik.org.

Summary

The following three PowerShell cmdlets (and some specific parameters which will be listed later) can combine to obtain just the Mac address of a device that has a Dhcp lease:

  • Get-DhcpServerv4Lease
  • Where-Object
  • Select-Object

Description

Rather self-explanatorily, Get-DhcpServerv4Lease will display information relating to all the leases contained in the specified scope, including the Mac address of our target device. This is a good start, but there is a lot of unwanted information being displayed. Let’s address that with some filtration.

Perhaps less self-explanatorily, Where-Object allows us to add a filtration criterion (or multiple filtration criteria) to our query. We will filter on the HostName property of the objects returned by Get-DhcpServerv4Lease so that only information pertaining to our target computer is displayed. We’ve now filtered out most of the unwanted information, but there is still some left. Let’s filter some more.

Definitely less self-explanatorily, Select-Object can perform even more filtration. We will filter on the ClientId property (which in this case is equivalent to the Mac address), thus discarding any information that is not the Mac address.

Show me the code!

When we put it all together with the help of the pipeline (note the “|” pipe character separating the cmdlets), it looks like this:

PS 7.2> $DhcpServerHostname     = "dhcpserver01"
PS 7.2> $DhcpScopeIpAddress     = "10.0.0.0"
PS 7.2> $TargetAbsoluteHostname = "pc01.example.domain"

PS 7.2> Get-DhcpServerv4Lease -ComputerName $DhcpServerHostname -ScopeId $DhcpScopeIpAddress | Where-Object -Property "HostName" -Like -Value $TargetAbsoluteHostname | Select-Object -ExpandProperty "ClientId"

01-23-45-67-89-AB

Notes

  1. Yes, unfortunately, the Ip address of the Dhcp scope is required.
    For some reason, the team behind this cmdlet decided they wouldn’t
    allow searching across all scopes. Very frustrating, as it seems
    such a glaring omission. If you need help finding the Ip address for
    your target scope/s, ask another question.
  2. The hostname I’ve used in the example is an absolute hostname. I
    would say it is more common for Dhcp entries to use the absolute
    name than not, hence the inclusion, but the relative hostname (i.e.
    pc01 in this case) may work instead. Alternatively, one could
    employ the use of a wildcard (i.e. an “*” asterisk in PowerShell), but
    an explanation of that might require a separate question be asked
    due to the added complexity it entails.

Update

Note, if you are looking to search for DHCP information across all or multiple DHCP servers in the forest then this is a quicker method. The below is still valid if you are searching a single server.

Sometimes in a large infrastructure it can be hard to find new devices added to the network. Being able to search on MAC address across all DHCP scopes comes in handy. With powershell and Windows DHCP server this is easy to do. You can use the RSAT tools or directly on the DHCP server. The only difference being with the RSAT tools you need to add the DHCP server name via the -ComputerName switch. To begin you can list all the leases on the current server with:

PS C:UsersAdministrator> Get-DhcpServerv4Scope | Get-DhcpServerv4Lease

Which should give you the following output:

Powershell DHCP Lease Search

That should be a full list of active leases, to narrow the results down by MAC address use:

PS C:UsersAdministrator> Get-DhcpServerv4Scope | Get-DhcpServerv4Lease -EA SilentlyContinue -ClientId 00-0c-29-dc-a5-3b

Resulting in:

Powershell DHCP Lease Search Filter

The -EA blocks any failures from scopes that do not have any matches so makes the output nicer. Another handy tip is a quick way to find a free IP in a defined DHCP scope:

PS C:UsersAdministrator> Get-DhcpServerv4FreeIPAddress -ScopeId 10.10.100.0
10.10.100.53

There comes a point when you ask yourself, ‘there has to be a better way’ (this should be often). This was certainly the case where after a large campus switch out which required many printers to be reconfigure. Part of that reconfiguring was creating new DHCP reservation.

Unfortunately, if you do not cull the old lease, Windows (rightfully so) informs you there is already a device with that MAC in the reservation database. In someone’s at Microsoft’s infinite wisdom, they neglect to tell you what DHCP scope the device is currently reserved in. So I would begin to trawl each scope I guessed in maybe reserved in based on my knowledge of our current scopes. This would waste many minutes of my time (sometimes without success) which means my customers are getting less of me. No good.

But, I did ask myself, ‘there has to be a better way’…and there is!

Open up a command prompt window on your DHCP server (or a remote powershell session) and input the following:

netsh dhcp server dump | find /i"MACADDRESS"

All you need is the MAC address of the device and input it without ‘-‘ in the MACADDRESS space and you should get something a little like the below:

dhcpdump

Another time saver for the time poor SysAdmin


Posted by TheAtul 2014-10-21T11:54:47Z

Hello all,

is there any way to find or find duplicate MAC address in DHCP scope.

Suppose I have scope1 192.168.105. *** and Scope2 192.168.106.*** one of the engineer has reserved the MAC in both the scopes and forgot the IPs he has assigned.

so is there any way to find duplicate MAC.

I exported the scope in .txt file and searched this works for is there any other way 

14 Replies

  • Author Robert Miller

    Rockn


    This person is a Verified Professional

    This person is a verified professional.

    Verify your account
    to enable IT peers to see that you are a professional.

    mace

    If this is a Windows server, in the DHCP snap-in look at the leases section and MAC addresses are to the far right.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Atul A

    Thanks Rockn.

    I am looking for any command or automated way to check this


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Lillebror Och Karlsson

    You can try command line at the server: “arp -a” or “arp -a >mac.txt” to output to the file (no quotes of course) 🙂


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Brit V8

    What version of OS?


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Atul A

    windows 2008 R2


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Brit V8

     

    TheAtul wrote:

    I am looking for any command or automated way to check this

    Here is a powershell script that will do what you want. It should work with 2008 R2

    http://britv8.com/dhcp-find-duplicate-mac-reservations-from-2012-r2-dhcp-server/ Opens a new window

    It reads all the scopes off your DHCP server, gets all the reservations , then shows you any reservations where the MAC address is used two or more times


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Atul A

    Ran the script and got the error below

    The term ‘Get-DhcpServerv4Scope’ is not recognized as the name of a cmdlet, function, script file, or operable program.

    Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

    At C:ScriptsDuplicateMACDHCP.PS1:26 char:32

    + $Scopes = Get-DhcpServerv4Scope <<<< -ComputerName $PrimaryDHCPServer

    + CategoryInfo : ObjectNotFound: (Get-DhcpServerv4Scope:String) [], CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Lillebror Och Karlsson

    TheAtul wrote:

    windows 2008 R2

    ARP with file output will work in your case just fine: “arp -a >mac.txt”


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Atul A

     “arp -a >mac.txt” will not list all the subnets.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Lillebror Och Karlsson

    Yes, it would, if all your DHCP scopes are hosted on the same server. You’d have to “-N” switch to specify adapter interface.  Then run it for each NIC in the server that hosts DHCP scope.

    With multiple servers you’d have to run this command on each server that hosts DHCP and combine output files for analysis.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Brit V8

    TheAtul wrote:

    Ran the script and got the error below

    The term ‘Get-DhcpServerv4Scope’ is not recognized as the name of a cmdlet, function, script file, or operable program.

    Ok, was worried about that…… looks like it is a powershell 4 cmdlet 

    If you have a windows 2012 R2 member server, you could run the script on there, maybe.

    Could also try Installing powershell 4 on the dhcp server

    http://social.technet.microsoft.com/wiki/contents/articles/21016.how-to-install-windows-powershell-4… Opens a new window


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Brit V8

    I can confirm my script this will work from a 2012 R2 Member server against a 2008 R2 dhcp server

    ETA can also confirm that Powershell 4 on 2008 R2 will not work, it must be run from a 2012 R2 or probably a 8.1 machine with RSAT tools installed


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Andrew Curtis

    I found this discussion looking for an answer to this myself. And with the help @britv8’s script I came up with this more succinct command which may be helpful for others also looking for an answer. 🙂 

    Powershell

    Get-DhcpServerv4Scope -ComputerName <dhcp_server> | Get-DhcpServerv4Lease -ComputerName <dhcp_server> | where{$_.clientid -eq "<MAC_address_with_dashes_instead_of_colons>" -or $_.hostname -like "*<hostname>*"}
    

    Just change your “where” clause to suit your needs.

    As @britv8 mentioned above, it must be run from 2012 R2 where the DHCP module can be found.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author shane hull

    $session = new-pssession -computername “SERVER”

    import-module dhcpserver -pssession $session

    🙂


    Was this post helpful?
    thumb_up
    thumb_down

Read these next…

  • Curated Snap! -- Seance AI, Simulated Alien Messages, Tech Majors, Radiation Antidote

    Snap! — Seance AI, Simulated Alien Messages, Tech Majors, Radiation Antidote

    Spiceworks Originals

    Your daily dose of tech news, in brief.

    Welcome to the Snap!

    Flashback: May 23, 1994: Java Development Begins in Earnest (Read more HERE.)

    Bonus Flashback: May 23, 2017: NASA astronauts take impromptu spacewalk (Read more HERE.)

    You ne…

  • Curated Spark! Pro Series - 23 May 2023

    Spark! Pro Series – 23 May 2023

    Spiceworks Originals

    Today in History: 23 May

     

    On this day in 1994, Sun Microsystems Inc.
    formally announced its new programs, Java and HotJava at the SunWorld ‘95
    convention. The concept was to design a programming language whos…

  • Curated Have you ever been a SpiceWorld speaker before?

    Have you ever been a SpiceWorld speaker before?

    Spiceworks

    Hey SpiceFriends!We are nearing the cut-off time for our Call to Speakers for SpiceWorld 2023!UPDATE: WE ARE EXTENDING SUBMISSIONS UNTIL MAY 26TH (FRIDAY)!Valerie (Spiceworks)​’s original post with the details is found here: https://community.spiceworks.c…

  • Curated Wild Wild WhatsApp West

    Wild Wild WhatsApp West

    Best Practices & General IT

    There has been a growing interest from employees in WhatsApp. We are finding that employees believe they need it to communicate with international clients as these clients prefer this method of communication. This is creating a little bit of a dilemma for…

  • Curated Failed domain join

    Failed domain join

    Windows

    I have two virtualized machines, server and client. I set up AD DS on the one as server. Went to domain join client to the server (with os windows server 2019 St. Ev.) and I’m receiving “0x0000251” error code.- The host (A) or (AAAA) records that map doma…

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