Implementing a TCP traceroute

0

I'm trying to understand the code below (found on the internet):

#!/usr/bin/python3

from scapy.all import *

target = input("Informe um alvo: ")
destport = input("Porta de destino: ")

port = int(destport)

ans,unans=sr(IP(dst=target,ttl=(1,30))/TCP(dport=port,flags="S"))
ans.summary(lambda s,r: r.sprintf("%IP.src%\t{ICMP:%ICMP.type%}\t{TCP:%TCP.flags%}"))

I can not understand the last line at all:

ans.summary(lambda s,r: r.sprintf("%IP.src%\t{ICMP:%ICMP.type%}\t{TCP:%TCP.flags%}"))

Could someone please explain in detail the last line of the program? Why use sprintf instead of print ? I found it very confusing ...

    
asked by anonymous 11.08.2016 / 01:18

1 answer

0
ans, unans = sr(IP(dst=target, ttl=(1, 30)) / TCP(dport = port, flags = "S"))

According to the documentation, sr is used to send packages, the result is a tuple with the packages and answers and unresponsive packages, and are assigned the variables ans and unans respectively.

dst is used to set target packages, ttl defines the lifetime of the package, each operating system has a different standard, for example, Linux can be 64 , in Windows it is 128 . In the code the ttl will be between 1 and 30 . Finally, the port is defined and flag indicating SYN .

ans.summary(lambda s,r: r.sprintf("%IP.src%\t{ICMP:%ICMP.type%}\t{TCP:%TCP.flags%}"))

The ans variable contains the resulting packages and responses of the sr function, the summary method is to show a summary of each package, lambda is a Python keyword that indicates an anonymous function of a line only, s and r are the arguments of that function ( in this question there is more information on the subject). Another way to do this would be like this:

for s, r in ans:
  print ("{} \t {} \t {}".format(r.scr, r[ICMP].type, r[TCP].flags))

Note : I did not test the above code!

sprintf is a function of Scapy itself in order to format the string with the values of the package fields, the format can include directives that start and end with % , for example : IP.src , ICMP.type , TCP.flags . In this link you can see the implementation.

For more information view the documentation .

    
19.08.2016 / 03:24