Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 799
Dave Forgac Avatar asked Jul 20 '09 05:07

Dave Forgac


People also ask

Is ping same as traceroute?

Ping and traceroute are common commands you can use to troubleshoot network problems. Ping is a simple command that can test the reachability of a device on the network. Traceroute is a command you use to 'trace' the route that a packet takes when traveling to its destination.

Which is better ping or traceroute?

The main difference between Ping and Traceroute is that Ping is a quick and easy utility to tell if the specified server is reachable and how long will it take to send and receive data from the server whereas Traceroute finds the exact route taken to reach the server and time taken by each step (hop).


1 Answers

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
like image 71
Andre de Miranda Avatar answered Sep 18 '22 06:09

Andre de Miranda