在python中,如何从附近的主机检索MAC地址?
我注意到,使用,我可以做到:在python中,如何从附近的主机检索MAC地址?,python,networking,mac-address,nmap,Python,Networking,Mac Address,Nmap,我注意到,使用,我可以做到: $ 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
$ 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']
但除非以root用户身份运行,否则nmap不会提供MAC地址。然而,当我关闭Python会话时,我可以立即运行arp-an
,并获得所有找到的主机及其相应MAC地址的转储
有没有一种干净的方法可以直接在Python中获取这些数据,而无需
arp
输出谢谢。来自python nmap的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'])
@mikepurvis在Linux上是正确的,我认为Mac是正确的。您需要以root用户身份运行python,才能使用nmap获取mac信息。我刚刚在服务器2019上尝试的Windows安装工作正常,但我的用户帐户在管理员组中 我已经在我的应用程序中发布了一个示例cli python脚本。此示例包括如何通过shell脚本使用pyenv以干净的方式以root用户身份运行python 下面是使用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)
#...
FWIW,在我的系统(Mepis 11)上,我需要是root才能运行
arp
。很有趣,谢谢你提供的信息。在Ubuntu和Mac OS X上,默认配置允许arp
作为非特权用户运行;除非您是root用户,否则您甚至不能运行ifconfig
。而且Mepis不启用sudo
默认情况下,您必须使用su
。OTOH,我也运行Puppy Linux,在那里以root用户身份运行是很正常的只有当整个程序以root用户身份运行时,才会填充mac
字段。