问题
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