gpt4 book ai didi

python - 使用 Scapy ping IP 范围

转载 作者:太空狗 更新时间:2023-10-29 21:40:53 25 4
gpt4 key购买 nike

我正在尝试编写一个 Python 脚本,该脚本使用 Scapy 模块来 ping 内部 IP 范围以确定哪些 IP 在线。到目前为止我已经知道了:

#!/usr/bin/python
from scapy.all import *
conf.verb = 0
for ip in range(0, 256):
packet = IP(dst="192.168.0." + str(ip), ttl=20)/ICMP()
reply = sr1(packet)
if "192.168." in reply.src:
print reply.src, "is online"

程序会静置一段时间什么都不做,然后如果我用 CTRL+C 终止它,我会收到一条错误消息:

Traceback (most recent call last):
File "sweep.py", line 7, in <module>
if "192.168." in reply.src:
AttributeError: 'NoneType' object has no attribute 'src'

但是,如果我尝试使用单个 IP 地址而不是范围,它会起作用。像这样:

#!/usr/bin/python
from scapy.all import *
conf.verb = 0
packet = IP(dst="192.168.0.195", ttl=20)/ICMP()
reply = sr1(packet)
if "192.168." in reply.src:
print reply.src, "is online"

有人知道我该如何解决这个问题吗?或者您对我如何使用 Scapy ping IP 范围以确定哪些主机在线有任何其他想法吗?

最佳答案

您只需要确保 reply 不是 NoneType 如下所示... sr1() 返回 None 如果您等待响应超时。您还应该向 sr1() 添加一个 timeout,默认超时对于您的目的来说是非常荒谬的。

#!/usr/bin/python
from scapy.all import *

TIMEOUT = 2
conf.verb = 0
for ip in range(0, 256):
packet = IP(dst="192.168.0." + str(ip), ttl=20)/ICMP()
reply = sr1(packet, timeout=TIMEOUT)
if not (reply is None):
print reply.dst, "is online"
else:
print "Timeout waiting for %s" % packet[IP].dst

关于python - 使用 Scapy ping IP 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7541056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com