How can I perform a ping or traceroute using native python?

Dave Forgac picture Dave Forgac · Jul 20, 2009 · Viewed 27.9k times · Source

I would like to be able to perform a ping and traceroute from within Python without having to execute the corresponding shell commands so I'd prefer a native python solution.

Answer

Andre de Miranda picture Andre de Miranda · Aug 11, 2011

If you don't mind using an external module and not using UDP or TCP, scapy is an easy solution:

from scapy.all import *
target = ["192.168.1.254"]
result, unans = traceroute(target,l4=UDP(sport=RandShort())/DNS(qd=DNSQR(qname="www.google.com")))

Or you can use the tcp version

from scapy.all import *
target = ["192.168.1.254"]
result, unans = traceroute(target,maxttl=32)

Please note you will have to run scapy as root in order to be able to perform these tasks or you will get:

socket.error: [Errno 1] Operation not permitted