8

我正在尝试编写一个 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+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'

但是,如果我尝试使用单个 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 范围以确定哪些主机在线有任何其他想法?

4

3 回答 3

7

您只需要确保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
于 2011-10-19T02:44:41.887 回答
2

如果变量的返回为空,则无法显示 reply.src 字段。换句话说,您需要验证变量是否返回了某个值(如果 ping 成功)。只有当变量不为空时,您才可以设置 IF 条件来获取 .src 字段。

于 2012-04-21T19:03:31.330 回答
1

FTR,Scapy 支持隐式生成器。这有效:

ans, unans = sr(IP(dst="192.169.0.1-255")/ICMP(), timeout=2) 

然后遍历答案。

它可能要好得多:)

于 2019-07-13T12:48:22.897 回答