簡體   English   中英

導入模塊時禁止scapy警告消息

[英]suppress scapy warning message when importing the module

我正在編寫一個小腳本,使用scapy收集一些信息,然后返回一些xml代碼,我將傳遞給metasploit的xmlrpc接口。 我希望我的腳本只返回xml,沒有其他警告等。

我可以通過向我的sr1命令添加選項verbose=0來抑制大多數scapy輸出。 我在每個輸出之前仍然得到的,並且我假設它在我加載模塊時返回此警告,是:

警告:找不到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.stder重新定義為None會引發異常AttributeError:'NoneType'對象沒有屬性'write' 相反,將它定義為os.devnull完成這項工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM