Capturing Scapy function output in Python

不想你离开。 提交于 2019-12-23 04:26:15

问题


I am trying to capture the output of a scapy function (traceroute) to a string in a python script. I understand I need to pipe this function to stdout (as you do with subproces.call() but unsure how to do this using scapy, is anybody able to provide any assistance? I am new to Python.

Relevent code below.

#!/usr/bin/env python
from scapy.all import traceroute

traceroute('www.google.com')

回答1:


You can also call traceroute like this:

trace, _ = traceroute("www.example.org", verbose=0)
# trace.get_trace() returns a rather impractical format, so we need
# to convert it. First, we only want the first trace available
hosts = trace.get_trace().values()[0]

# hosts will be in the format { 1: ("1.2.3.4",     False), 
#                               2: ("10.20.30.40", False) ... }
# We convert it to ["1.2.3.4", "10.20.30.40", ...] here:
ips = [hosts[i][0] for i in range(1, len(hosts) + 1)]

After which the ips variable will contain a list of the hosts that are part of the trace.




回答2:


You can do that by patching sys.stdout with a file-like object (for example StringIO):

#!/usr/bin/env python                              
from scapy.all import traceroute
from StringIO import StringIO
import sys

stdout = StringIO()
sys.stdout = stdout
result, unanswered = traceroute('www.google.com')
sys.stdout = sys.__stdout__

print 'Captured stdout:', stdout.getvalue()

Anyway, please note that the information that you need is probably already in the objects returned by the traceroute method:

print result.summary()                                      
print unanswered.summary()

Note: You can find more information about patching the standard output in the answers to this question.



来源:https://stackoverflow.com/questions/8610172/capturing-scapy-function-output-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!