A MAC (Media Access Control) address is a unique number assigned to a network adapter. In most cases, MAC address is displayed as a string of six hexadecimal numbers which separated by colons (e.g. DC:A6:32:E1:5B:4B
). First three hexadecimal numbers (e.g. DC:A6:32
) is called OUI (Organizationally Unique Identifier). OUI identifies the manufacturer.
This tutorial provides example to find devices by OUI connected to local network using Nmap and Python.
Prepare environment
Make sure you have installed Nmap and Python on your system. On Windows, make sure that Nmap directory is added to the PATH environment variable.
Using pip
package manager install python-nmap
library that allows to use Nmap and get scan results:
pip install python-nmap
Code
We have defined target
a variable that specifies IP range of the network from 192.168.0.0 to 192.168.0.255. To determine that, use ip
command on Linux or ipconfig
command on Windows.
In our case, we will try to find Raspberry Pi boards connected to the local network. OUI of Raspberry Pi manufacturer is B8:27:EB
or DC:A6:32
.
Nmap accepts -sn
option. It means that Nmap will scan devices on the network without port scan phase. On Linux, Nmap command must be executed with sudo to include the MAC address of each device in scan results.
import nmap
target = '192.168.0.0/24'
oui_list = ['B8:27:EB', 'DC:A6:32']
scanner = nmap.PortScanner()
scanner.scan(target, arguments='-sn', sudo=True)
hosts = []
for host in scanner.all_hosts():
addresses = scanner[host]['addresses']
if 'mac' not in addresses:
continue
oui = addresses['mac'][:8]
if oui in oui_list:
hosts.append(addresses)
print(hosts)
If devices has been found, you will get results in the following form:
[{'ipv4': '192.168.0.100', 'mac': 'DC:A6:32:E1:5B:4B'}, {'ipv4': '192.168.0.123', 'mac': 'B8:27:EB:65:A1:2C'}]
Leave a Comment
Cancel reply