导入模块时抑制Scapy警告消息



我正在编写一个小脚本,该脚本使用scapy收集一些信息,然后返回一些XML代码,这些代码将传递到Metasploit的XMLRPC接口。我希望我的脚本只返回XML,并且没有其他警告等。

我可以抑制大多数Scapy输出,并将选项verbose=0添加到我的SR1命令中。在每个输出之前,我仍然会得到什么,我认为加载模块时它会返回此警告,为:

警告:没有找到IPv6目标::(没有默认路线的路线?)

我可以通过这样的脚本来轻松地重定向输出:

 ./myscript 2> /dev/null

,但我想将其纳入脚本。为此,我找到了一个提示,可以有一个nulldevice类,没有写任何东西,然后将sys.stderr设置为nulldevice类的实例化。

不幸的是,这仅在我已经加载该模块之后才起作用,因此我仍然有警告,并且仅将以下任何发送到STDERR的消息重定向。

我如何抑制该警告消息以显示在屏幕上?

您可以通过添加:

来摆脱Scapy的警告
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)

进口Scapy。这将压制所有与错误消息相比,严重程度较低的消息。


例如:

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
...

我认为这是正确的方法。

>>> import sys
>>> sys.stderr = None            # suppress stderr
>>> from scapy.all import *
>>> sys.stderr = sys.__stderr__  # restore stderr
>>> print("other errors can be shown", file=sys.stderr)
other errors can be shown
>>> 

我认为Scapy的python3版本也可能从其他记录器或高级别打印出消息。这是我用来抑制模块导入输出的一些代码。

from contextlib import contextmanager
# It looks like redirect_stderr will be part of Python 3.5 as follows:
# from contextlib import redirect_stderr
# Perhaps if you're looking at this code and 3.5 is out, this function could be
# removed.
@contextmanager
def redirect_stderr(new_target):
    """
    A context manager to temporarily redirect stderr. Example use:
    with open(os.devnull, 'w') as f:
        with redirect_stderr(f):
            # stderr redirected to os.devnull. No annoying import messages
            # printed on module import
            from scapy.all import *
    # stderr restored
    """
    import sys
    old_target, sys.stderr = sys.stderr, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stderr = old_target # restore to the previous value

# Don't print the annoying warning message that occurs on import
with open(os.devnull, 'w') as errf:
    with redirect_stderr(errf):
        from scapy.all import sr, ICMP, IP, traceroute

带有python3,重新定义sys.stderr to none丢下异常 attributeError:'nontype'对象没有属性'写入'write'。相反,将其定义到os.devnull完成工作:

import os
import sys
sys.stderr = os.devnull # suppress stderr
from scapy.all import *
sys.stderr = sys.__stderr__ # restore stderr

最新更新