0

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')

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh great this looks like the perfect solution, can you explain the second line for me I am unsure where you got the class 'a' from
of course it should be trace. Editing it and adding a few comments also
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.