使用Scapy ping IP范围

use*_*124 7 python ping scapy

我正在尝试编写一个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"
Run Code Online (Sandbox Code Playgroud)

该程序将暂时无所事事,然后如果我用CTRL + CI杀死它会得到一条错误消息:

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'
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试使用单个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"
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*ton 6

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

#!/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
Run Code Online (Sandbox Code Playgroud)