suppress scapy warning message when importing the module

后端 未结 4 1842
無奈伤痛
無奈伤痛 2021-02-19 09:06

I\'m writing a small script, that gathers some information using scapy and then returns some xml code, that I\'ll pass on to the xmlrpc interface of metasploit. I\'d like it tha

4条回答
  •  一个人的身影
    2021-02-19 09:39

    I think perhaps the python3 version of scapy prints a message from a different logger or at a high level. Here's some code I've used to suppress output on module import.

    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
    

提交回复
热议问题