Skip to content

Instantly share code, notes, and snippets.

@en0
Created July 26, 2014 03:22
Show Gist options
  • Save en0/f5ed8262e28cad66eff1 to your computer and use it in GitHub Desktop.
Save en0/f5ed8262e28cad66eff1 to your computer and use it in GitHub Desktop.
My traceroute program in python using scapy.
#!/bin/usr/env python2
from scapy.all import *
from argparse import ArgumentParser
from sys import argv
from time import time
# shut up scapy
conf.verb=0
def trace(ttl, max_ttl, dst, payload, try_count=0):
if ttl > max_ttl : return
p = IP(ttl=ttl, dst=dst)
st = time()
r = sr1(p/ICMP()/payload, timeout=1)
et = time()
print("{0:<4} : {1:<18} : {2}ms".format(
str(ttl),
r.src if r else "No Reply",
int((et-st)*1000))
)
if r and r.src == dst:
return True;
elif not r and try_count < 2:
return trace(ttl, max_ttl, dst, payload, try_count+1)
return trace(ttl+1, max_ttl, dst, payload);
def tracepath(ttl, max_ttl, dst, payload):
print("\nTracing route to {} over a maximum of {} hops...\n".format(dst, max_ttl));
print("{0:<4} : {1:<18} : {2}".format("#","HOST","TIME"))
st = time()
success = trace(ttl, ttl+max_ttl-1, dst, payload)
et = time()
if success:
print("\nFound {} in {}ms. Trace complete".format(dst, int((et-st)*1000)))
else:
print("\nCould not trace {} in {} hops. Failed in {}ms.".format(dst, max_ttl, int((et-st)*1000)))
if __name__ == "__main__":
p = ArgumentParser();
p.add_argument('HOST', help="The ip address of the target")
p.add_argument('-p', type=str, default="ABCDEFG", help="The data to send in the IMCP packet.")
p.add_argument('-t', type=int, default=1, help="Start with this hop. (default: 1)")
p.add_argument('-m', type=int, default=1500, help="Maximum count of hops (default: 1500)")
arg = p.parse_args(argv[1:])
tracepath(arg.t, arg.m, arg.HOST, arg.p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment