繁体   English   中英

在 Python / Scapy 网络扫描仪中按 MAC 地址过滤/标记设备标识的打印结果

[英]Filtering / Labeling Print Results for Device Identification by MAC Address in a Python / Scapy Network Scanner

我是初学者,但我正在尝试制作一个网络扫描实用程序,可以根据特定需求过滤 MAC 地址; 我工作的公司拥有基于序列号分配 MAC 地址的联网设备。 我发现MAC地址的前6位是我们品牌的标志。 这我在下面做了一个str。 MAC 地址的第 4 个字段是一个小范围的常数,表示设备的型号。 我准备好了这些,但本质上是一些数字,如“14”、“17”等。

我正在努力找出一种方法来“过滤”从扫描中检索到的 MAC 地址,并根据地址的字段标记它们。 或者更好的是,只打印与startswith(mac_key)匹配的IP和Mac地址,并根据MAC地址第4个字段[9:11]标记剩余的对象。

通过大量阅读和帮助,到目前为止我已经做到了:

    #!/usr/bin/env python
from scapy.all import ARP, Ether, srp
import socket
# importing main functions from Scapy and Socket

mac_key = '04:24:2f'
# Target value for first three fields of MAC address

hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
target_ip = ("192.168.{}.0/24".format(IPAddr[6]))
# Assigning index value for third section of IP address
# To make third section of target_ip a variable determined by host
# "/24" denotes IP address spectrum for the ARP packet destination

arp = ARP (pdst=target_ip)
# Creating ARP packet assigned to "target_ip"

ether = Ether(dst="ff:ff:ff:ff:ff:ff")
# Creating Ether broadcast packet
# ff:ff:ff:ff:ff:ff MAC address indicates broadcasting

packet = ether/arp
# Stacking

result = srp(packet, timeout=5, verbose=3)[0]
# Defining result with timeout parameter

clients= []
# Client list to be finished below

for sent, received in result:
    clients.append({'ip': received.psrc, 'mac': received.hwsrc})
    # For each response, append ip and mac address to 'clients' list

print("Devices On This Network:")
print("IP" + " "*18+"MAC")
# Print table of accumulated data

for client in clients:
    print("{:24}    {}".format(client['ip'], client['mac'].startswith(mac_key)))
# Printing IP addresses and assosciated MACs from clients list
# With bool checking against mac_key

下图是终端中的结果; 这个想法是只打印显示 TRUE 值的行,并根据 MA​​C 地址的字段 [9:11] 添加一个标签,例如:“Network Device Pro” TRUE bool 出现的地方,并完全省略该行触发了 FALSE 布尔值。

编辑:嗯,我已经把它变成了一个博客。 我设法做到了我想做的事情,并且我将为任何试图做类似事情的人提供下面的代码。 我愿意接受任何建议,使其更加“pythonic”并提高性能/语法。 对于任何可以提供建议的人,我确实有一个问题; 我想循环此代码并将信息附加到呈现的列表中,并包含一个用户输入终止开关来完成它。 这样,如果数据包在第一次扫描时没有到达,它仍将被添加到列表中。 如果您可以为此提供建议,以及一种删除连续循环次数后没有响应的条目的方法,则可以加分!!

#!/usr/bin/env python3
# coding: utf-8
#
#
#//////////////////////////////////
#----------------------------------
# ippy Network Scanning Utility
#   ~ Daniel Johnston 2020 ~
#----------------------------------
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
#
#
print("Initializing Scan...")
from scapy.all import ARP, Ether, srp
import socket
# importing main functions from Scapy and Socket

mac_key = ('00:25:2f')
# Target value for first three fields of MAC address (Brand Identifier)

MTU_key = ('13','15','16','17')
GW_key = ('21')
ECC_key = ('26')

#------serial numbers)------#

#('13','15','16','17','21','26'#

#---------LEGEND------------#
#serial numbers[0:3] = 'MTU'
#serial numbers[4] = 'Gateway'
#serial numbers[5] = 'ECC'
#---------------------------#

hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
target_ip = ("192.168.{}.0/24".format(IPAddr[6]))
# Assigning index value for third section of IP address
# To make third section of target_ip a variable determined by host
# "/24" denotes IP address spectrum for the ARP packet destination

def devsub(x):
        if x.startswith(MTU_key, 9, 11):
            print("{}   {}".format('MTU', client['ip'],))
        if x.startswith(GW_key, 9, 11):
            print("{}   {}".format('Gateway', client['ip'],))
        if x.startswith(ECC_key, 9, 11):
            print("{}   {}".format('ECC', client['ip'],))
# Defining function to print associated IP addresses, of MAC address    
# Matches(done later), and assigning a device name based on     
# index[9:11] of MAC

arp = ARP (pdst=target_ip)
# Creating ARP packet assigned to "target_ip"

ether = Ether(dst="ff:ff:ff:ff:ff:ff")
# Creating Ether broadcast packet
# ff:ff:ff:ff:ff:ff MAC address indicates broadcasting

packet = ether/arp
# Stacking

result = srp(packet, timeout=5, verbose=3)[0]
# Defining result with timeout parameter

clients= []
# Client list to be finished below

for sent, received in result:
    clients.append({'ip': received.psrc, 'mac': received.hwsrc})
# For each response, append ip and mac address to 'clients' list

print("~"*20)
print("-"*20)
print("Devices On This Network:")
print("-"*20)
print("Device" + " " * 4 + "IP Address")
#Text formatting
for client in clients:
    if client['mac'].startswith(mac_key):
        devsub(client['mac'])
#Running primary filter to only include MAC addresses that pass
# .startswith(mac_key) into devsub function to print device name 
# Associated with MAC[9:11] variables, and the appropriate IP address

所以这是电流输出,有1个匹配设备

在此处输入图片说明

使用 scapy 内置函数比重写它们更有意义。 在这种情况下,请使用arping 为了节省使用 scapy 的时间(如这里),您应该阅读手册

这会将第 4 个八位字节打印到文件中:

from scapy.all import arping

local_devices = arping("192.168.1.0/24")
local_macs = [device[1].src for device in local_devices[0]]
fourth_octets = [mac[9:11] for mac in local_macs]
with open("fourth_octets.txt", "w") as f:
     f.write("\n".join(fourth_octet))

Scapy解释器中的解释

>>> # Get local devices. Four have been found, and 252 provided no answer.
>>> local_devices = arping("192.168.128.0/24")
>>> local_devices
(<ARPing: TCP:0 UDP:0 ICMP:0 Other:4>,
 <Unanswered: TCP:0 UDP:0 ICMP:0 Other:252>)

>>> # Get the mac addrs of each of the ARP responses with a list comprehension
>>> local_macs = [device[1].src for device in local_devices[0]]
>>> local_macs
['e0:55:3d:4d:e4:58',
 '00:18:0a:27:26:ee',
 'e0:55:3d:d2:0a:12',
 '38:53:9c:08:b9:9f']

>>> # Get the fourth octet by string position in the macs
>>> fourth_octets = [mac[9:11] for mac in local_macs]
>>> fourth_octets
['4d', '27', 'd2', '08']

>>> # Write to the file with the fourth octets, each on a line
>>> with open("fourth_octets.txt", "w") as f:
     f.write("\n".join(fourth_octets))

>>> # Verify that the text file looks as expected
>>> with open("fourth_octets.txt") as f:
     print(f.read())

4d
27
d2
08

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM