Reputation: 1628
I note that with python-nmap, I can do this:
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import nmap
>>> n = nmap.PortScanner()
>>> n.scan(hosts='192.168.1.0/24', arguments='-sP')
{'nmap': {'scanstats': {'uphosts': u'6', 'timestr': u'Sat Oct 4 21:10:10 2014', 'downhosts': u'250', 'totalhosts': u'256', 'elapsed': u'2.69'}, 'scaninfo': {}, 'command_line': u'nmap -oX - -sP 192.168.1.0/24'}, 'scan': {u'192.168.1.104': {'status': {'state': u'up', 'reason': u'conn-refused'}, 'hostname': u'Mikes-MBP', 'addresses': {u'ipv4': u'192.168.1.104'}}, u'192.168.1.131': {'status': {'state': u'up', 'reason': u'conn-refused'}, 'hostname': u'Aidana', 'addresses': {u'ipv4': u'192.168.1.131'}}, u'192.168.1.133': {'status': {'state': u'up', 'reason': u'conn-refused'}, 'hostname': u'vm-trusty-desktop', 'addresses': {u'ipv4': u'192.168.1.133'}}, u'192.168.1.135': {'status': {'state': u'up', 'reason': u'conn-refused'}, 'hostname': u'android-d79f5b3256db8e11', 'addresses': {u'ipv4': u'192.168.1.135'}}, u'192.168.1.1': {'status': {'state': u'up', 'reason': u'syn-ack'}, 'hostname': '', 'addresses': {u'ipv4': u'192.168.1.1'}}, u'192.168.1.129': {'status': {'state': u'up', 'reason': u'syn-ack'}, 'hostname': u'DiskStation', 'addresses': {u'ipv4': u'192.168.1.129'}}}}
>>> n.all_hosts()
[u'192.168.1.1', u'192.168.1.104', u'192.168.1.129', u'192.168.1.131', u'192.168.1.133', u'192.168.1.135']
But nmap will not cough up MAC addresses unless you run it as root. And yet, when I close the Python session, I can immediately run arp -an
and get a dump of all the found hosts and their corresponding MAC addresses.
Is there a clean way to get this data directly in Python, without
arp
output?Thanks.
Upvotes: 2
Views: 10035
Reputation: 4485
@mikepurvis is correct on Linux and I assume Mac. You need to be running python as root to get mac information using nmap. The installation on Windows I just tried on Server 2019 worked just fine but my user account is in Administrator group.
I have posted a sample cli python script in my GitHub. This example includes how to run python as root in a clean way with pyenv through a shell script.
Here is a snip of the logic for scraping the information using nmap
#...
nm = nmap.PortScanner()
nm.scan(hosts='192.168.1.0/24', arguments='-sP')
for ip in nm.all_hosts():
host = nm[ip]
mac = "-"
vendorName = "-"
if 'mac' in host['addresses']:
mac = host['addresses']['mac']
if mac in host['vendor']:
vendorName = host['vendor'][mac]
status = host['status']['state']
rHost = {'ip': ip, 'mac': mac, 'vendor': vendorName, 'status': status}
print(rHost)
#...
Upvotes: 1
Reputation: 2909
From python-nmap's example.py:
# Vendor list for MAC address
nm.scan('192.168.0.0/24', arguments='-O')
for h in nm.all_hosts():
if 'mac' in nm[h]['addresses']:
print(nm[h]['addresses'], nm[h]['vendor'])
Upvotes: 2