用Scapy ping IP范围 [英] Pinging an IP range with Scapy
问题描述
我正在尝试编写一个Python脚本,该脚本使用Scapy模块对内部IP范围执行ping操作,以确定哪些IP在线.到目前为止,我已经知道了:
I'm attempting to write a Python script which uses the Scapy module to ping an internal IP range to determine which IP's are online. I've got this so far:
#!/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杀死它,则会收到一条错误消息:
And the program will sit for a while doing nothing, and then if I kill it with CTRL+C I get an error message:
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地址而不是一个范围尝试它,它将起作用.像这样:
However if I try it with a single IP address, instead of a range, it works. Like this:
#!/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范围来确定哪些主机处于联机状态有其他想法?
Anyone know how I can fix this problem? Or do you have any other ideas on how I can ping an IP range with Scapy, to determine which hosts are online?
推荐答案
您只需要确保reply
不是NoneType
,如下所示... sr1()
如果超时等待返回None
为回应.您还应该在sr1()
上添加timeout
,对于您的用途而言,默认超时是非常荒谬的.
You just need to ensure that reply
is not NoneType
as illustrated below... sr1()
returns None
if you get a timeout waiting for the response. You should also add a timeout
to sr1()
, the default timeout is quite absurd for your purposes.
#!/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
这篇关于用Scapy ping IP范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!