如何在Python中使用Scapy制作网络扫描仪?

2021年11月16日16:36:45 发表评论 1,012 次浏览

Python如何制作网络扫描仪?本文使用 ARP 请求构建一个简单的网络扫描器,并使用 Python 中的 Scapy 库监控网络。

网络扫描仪是网络管理员和渗透测试员的重要元素。它允许用户映射网络以查找连接到同一网络的设备。

如何使用Scapy制作网络扫描仪?在本教程中,你将学习如何使用Python 中的Scapy库构建一个简单的网络扫描仪。

相关文章: 如何在 Python 中制作子域扫描仪。

我假设你已经安装了它,如果不是这样,请随时查看这些教程:

也可以参考Scapy 的官方文档

Python如何制作网络扫描仪?回到正题,有很多方法可以扫描单个网络中的计算机,但我们将使用一种流行的方法,即使用ARP请求。

Python制作网络扫描仪示例介绍 - 首先,我们需要从scapy导入基本方法:

from scapy.all import ARP, Ether, srp

其次,我们需要发出一个ARP 请求,如下图所示:

如何在Python中使用Scapy制作网络扫描仪?

网络扫描器将发送 ARP 请求,指出谁拥有某个特定的 IP 地址,假设为"192.168.1.1",该 IP 地址的所有者(目标)将自动响应说他是"192.168.1.1",并带有该响应,MAC地址也将包含在数据包中,这允许我们在发送广播数据包(向网络中的所有设备发送数据包)时同时成功检索所有网络用户的IP和MAC地址。

ARP响应如下图所示:

如何在Python中使用Scapy制作网络扫描仪?

所以,让我们制作这些数据包:

target_ip = "192.168.1.1/24"
# IP Address for the destination
# create ARP packet
arp = ARP(pdst=target_ip)
# create the Ether broadcast packet
# ff:ff:ff:ff:ff:ff MAC address indicates broadcasting
ether = Ether(dst="ff:ff:ff:ff:ff:ff")
# stack them
packet = ether/arp

注意:如果你不熟悉 IP 地址后面的符号“/24”或“/16”,这里基本上是一个 IP 范围,例如,“192.168.1.1/24”是从“192.168”开始的范围。 1.0" 到 "192.168.1.255",请阅读更多关于 CIDR Notation 的信息

Python如何制作网络扫描仪?现在我们已经创建了这些数据包,我们需要使用srp()在第 2 层发送和接收数据包的函数发送它们,我们将超时设置为 3,这样脚本就不会卡住:

result = srp(packet, timeout=3)[0]

结果现在是格式对的列表(sent_packet, received_packet),让我们迭代它们:

# a list of clients, we will fill this in the upcoming loop
clients = []

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

如何使用Scapy制作网络扫描仪?现在我们需要做的就是打印我们刚刚填写的这个列表:

# print clients
print("Available devices in the network:")
print("IP" + " "*18+"MAC")
for client in clients:
    print("{:16}    {}".format(client['ip'], client['mac']))

下面是完整Python制作网络扫描仪示例代码:

from scapy.all import ARP, Ether, srp

target_ip = "192.168.1.1/24"
# IP Address for the destination
# create ARP packet
arp = ARP(pdst=target_ip)
# create the Ether broadcast packet
# ff:ff:ff:ff:ff:ff MAC address indicates broadcasting
ether = Ether(dst="ff:ff:ff:ff:ff:ff")
# stack them
packet = ether/arp

result = srp(packet, timeout=3, verbose=0)[0]

# a list of clients, we will fill this in the upcoming loop
clients = []

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

# print clients
print("Available devices in the network:")
print("IP" + " "*18+"MAC")
for client in clients:
    print("{:16}    {}".format(client['ip'], client['mac']))

这是我在个人网络中的结果截图:

如何在Python中使用Scapy制作网络扫描仪?
Python制作网络扫描仪示例

好的,我们完成了本教程,看看你如何扩展它并使其更方便地替换其他扫描工具。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: