Wrote a little thing about tracking routing in Python.

Source: Internet
Author: User

Reprint: http://www.iteye.com/topic/550804

collect.py, this can only be used under Linux ... #!/usr/bin/python

Because the traceroute command is used

Import sysimport osimport threadimport cpickleimport timeimport refrom socket import inet_ntoafrom subprocess import Popen  , Pipeimport dpkttry:import pcapexcept importerror:print "Failed to import pcap library!" Print "If you is using Debian/ubuntu Linux, please:" Print "[email protected]:~# apt-get install Python-pypcap" s  Ys.exit (1) class Tracertexception (Exception): Passdef tracert (host): "" "Traceroute eg:l = tracert (" 8.8.8.8 ") Return   VALUE:A List of routers "" "" P = Popen (["Traceroute", "-N", "-Q", "2", "-I", host], Stdout=pipe, Stderr=pipe) p.wait () (o, e) = P.communicate () if E! = ': E = e.replace ("\ n", "") Raise Tracertexception (e) t = [] r = Re.compil E (R "(\d{1,3}\.) {3}\d{1,3}) # matches a IP address for i in O.split ("\ n") [1:-1]: # Prompt at head and empty line at tail s = R. Search (i) if S:t.append (S.group ()) Else:t.append (None) del P return tdef thread_func (ARG): "THR EAD func, Trace route and store inRmap "Global Rmap, Rmap_lock, Taskqueue, Taskqueue_lock, Ending_flag Global ThreadCount, Threadcount_lock, My_ip, Tracke        D, Tracked_lock try:threadcount_lock.acquire () ThreadCount = threadcount + 1 threadcount_lock.release () While True:while not Len (taskqueue): Time.sleep (1) if ending_flag:threadcount_lock.a Cquire () ThreadCount = Threadcount-1 threadcount_lock.release () #print "Thread%d is Terminat ed. "% Thread.get_ident () thread.exit () if Ending_flag:threadcount_lock.acquire () THREADC        Ount = Threadcount-1 threadcount_lock.release () #print "Thread%d is terminated."% thread.get_ident ()        Thread.exit () Taskqueue_lock.acquire () If Len (taskqueue): IP = taskqueue.pop (0) Else: Taskqueue_lock.release () continue taskqueue_lock.release () print "Thread%d got work to do:%s" % (Thread.get_ident (), Ip) route = tracert (IP) tracked_lock.acquire () for I in Route : Tracked[i] = 1 # None is OK, I think, so not filtering tracked_lock.release () print "%s:%s          "% (IP, repr (route)) F = my_ip h = 1 Rmap_lock.acquire () for t in route:if t = = None: H = H + 1 continue rmap[(f,t)] = h H = 1 F = T if h! = 1:rmap[(F, None)] = IP # missing rmap_lock.release () except Exception, E:import traceback threadcount_lock.a Cquire () ThreadCount = Threadcount-1 threadcount_lock.release () print "Thread%d is *crashed*!"% (thread.get_i Dent (),) print Traceback.format_exc () thread.exit () def get_ifaddr (IFN): "" "Get IP address of specified Iface & Gt;>> get_ifaddr ("Wlan0") "113.121.xx.xx" "" "import struct, socket, fcntl s = socket.socket () return socket . Inet_ntoa (Fcntl.ioctl (s. Fileno (), 0x8915, Struct.pack ("256s", ifn[:15]) [20:24]) def main (): Global Rmap, Rmap_lock, Taskqueue, Taskqueue_lock, Ending_flag Global ThreadCount, Threadcount_lock, tracked, Tracked_lock, my_ip if Len (SYS.ARGV) < 2:print "Ple    ASE Specify a network interface! "    Sys.exit (1) if Os.geteuid (): print "This tool require root privilege to run!"    Sys.exit (1) If os.path.exists ("Routemap.dat"): # Is there a saved router map? Print "Loading saved route map ..." f = open ("Routemap.dat", "RB") Rmap, my_ip = Cpickle.load (f) f.close () my _ip = Get_ifaddr (sys.argv[1]) # add my IP to tracked tracked[my_ip] = 1 # Start working threads for I in xrange (20 ): Thread.start_new_thread (Thread_func, (None)) # start packet Capture try:p = Pcap.pcap (sys.argv[1]) F Or I in p:pkt = Dpkt.ethernet.Ethernet (i[1]) and not isinstance (PKT, str): PKT = Pkt.data if is Instance (PKT, Dpkt.ip.IP): src = Inet_ntoa (pkt.src)          DST = Inet_ntoa (PKT.DST) #print "%s =%s"% (SRC, DST) if not tracked.get (SRC):            TRACKED[SRC] = 1 print "Task:%s"% src Taskqueue_lock.acquire () taskqueue.append (SRC)            Taskqueue_lock.release () If not tracked.get (DST): tracked[dst] = 1 Print "Task:%s"% DST Taskqueue_lock.acquire () taskqueue.append (DST) taskqueue_l Ock.release () except keyboardinterrupt:intr = True if taskqueue_lock.locked (): Taskqueue_lock.relea SE () If intr:print "waiting for all thread to terminate ..." Try:ending_flag = True while Threadcoun T:print threadcount time.sleep (1) except Keyboardinterrupt:print "OK, OK, I'll terminate Immediatl Y ... "sys.exit (1) # Save the result print" Saving route map ... "f = open (" Routemap.dat "," WB ") Cpickle.du MP ((Rmap, my_ip), F, 2) F.close () print "program terminated." Sys.exit (0) class Dbglock:def __init__ (self, name): Self.lock = Thread.allocate_lock () self.name = name Def acqu IRE (self): Self.lock.acquire () print ":: Thread%d Locking%s"% (Thread.get_ident (), Self.name) def release (self ): print ":: Thread%d releasing%s"% (Thread.get_ident (), Self.name) self.lock.release () def locked (self): RET  Urn self.lock.locked () #----------------------------------------------------rmap = {} # Router map, all things goes here.  This should is saved. #rmap_lock = Thread.allocate_lock () Rmap_lock = Dbglock ("Rmap") Taskqueue = [] # task queue, IPs going To be tracked#taskqueue_lock = Thread.allocate_lock () Taskqueue_lock = Dbglock ("Taskqueue") tracked = {} # ips already TRAC Erouted#tracked_lock = Thread.allocate_lock () Tracked_lock = Dbglock ("tracked") Ending_flag = False # whether to end Collec Ting...threadcount = 0#threadcount_lock = Thread.allocate_lock () Threadcount_lock = Dbglock ("ThreadCount") my_IP = "" If __name__ = = "__main__": Main () 

drawgraph_graphviz.py

#!/usr/bin/pythonimport sysimport cpickleimport yapgvbimport randomdef Main (): def get_vertex_info (IP): if Nodetree.      Get (IP): # is source IP node already exist? VV = nodetree[ip][0] # vertex VL = nodetree[ip][1] # child vertex list ELSE:VV = G.add_node (IP) #v V.shape = "Circle" Vv.color = "Blue" VL = [] nodetree[ip] = (VV, VL) return (VV, VL) Nodetree = {    } filename = "Routemap.dat" If Len (SYS.ARGV) < 2:print "didn ' t specify filename, use ' Routemap.dat '" Else: filename = sys.argv[1] f = open (filename, "RB") Rmap, my_ip = Cpickle.load (f) f.close () G = Yapgvb. Digraph ("Routemap") Get_vertex_info (my_ip) [0].color = "green" for V, deg in Rmap.items (): Vertex, Vertexlist  = Get_vertex_info (v[0]) dup = False for IP, data in vertexlist:if IP = = v[1]: # The is a duplicate DUP      = True if Dup:continue if v[1] is not None: # is it a LOST trace? If deg> 1:for i in range (1, deg): VT = G.add_node ("*%d"% random.randint (0,100000000)) Vt.color =      "Red" vertex >> vt vertex = vt vertex_t, vertex_tlist = Get_vertex_info (v[1]) if vertex = = Vertex_t:print v Else:edge = vertex >> vertex_t vertexlist.append ((V[1], ed GE)) else:vertex_t = G.add_node ("LOST (%s)"% deg) Vertex_t.color = "Red" if vertex = = V Ertex_t:print v Else:edge = vertex >> vertex_t g.layout (yapgvb.engines.dot) print "Render ing ... "g.render (" Result.svg ") if __name__ = =" __main__ ": Main ()

  

Wrote a little thing about tracking routing in Python.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.