How can I perform a ping or traceroute using native python?
Solution 1
Running interpreters as root is often frowned upon on security grounds (and of course you DO need to have root permission to access the "raw" socked as needed by the ICMP specs of ping and traceroute!), but if you have no problems with that it's not hard -- e.g., this post(dead?) or this post give a workable ping, and Jeremy Hylton's old page has still-usable underlying code for ICMP (both ping and traceroute) though it's written for very old Python versions and needs a litte facelift to shine with modern ones -- but, the concepts ARE all there, in both the URLs I gave you!
Solution 2
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
Solution 3
The mtrpacket package can be used to send network probes, which can perform either a ping or a traceroute. Since it uses the back-end to the mtr commandline tool, it doesn't require that your script run as root.
It also uses asyncio's event loop, so you can have multiple ongoing traceroutes or pings simultaneously, and deal with their results as they complete.
Here is a Python script to traceroute to 'example.com':
import asyncio
import mtrpacket
async def trace():
async with mtrpacket.MtrPacket() as mtr:
for ttl in range(1, 256):
result = await mtr.probe('example.com', ttl=ttl)
print(result)
if result.success:
break
asyncio.get_event_loop().run_until_complete(trace())
The loop with 'ttl' is used because the 'time-to-live' of an outgoing packet determines the number of network hops the packet will travel before expiring and sending an error back to the original source.
Solution 4
The Webb Library is very handy in performing all kinds of web related extracts...and ping and traceroute can be done easily through it. Just include the URL you want to traceroute to:
import webb
webb.traceroute("your-web-page-url")
If you wish to store the traceroute log to a text file automatically, use the following command:
webb.traceroute("your-web-page-url",'file-name.txt')
Similarly a IP address of a URl (server) can be obtained with the following lines of code:
print(webb.get_ip("your-web-page-url"))
Hope it helps!
Dave Forgac
Updated on February 14, 2020Comments
-
Dave Forgac over 4 years
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.
-
Glenn Maynard almost 15 yearsIt's entirely possible to ping and traceroute without raw sockets or ICMP, with UDP packets. Many tools do this.
-
Alex Martelli almost 15 years@Glenn, that's not compatible with the actual ping and traceroute commands: if your counterparts support UDP echoes, these pseudo-ping and -traceroute versions will work, but, without ICMP, you're outside of the standard, and your checks might perfectly well fail (without a counterpart complying beyond standards) where the standard ICMP-based approaches would work.
-
Dave Forgac almost 15 yearsThanks. I guess I'm going to go back to trying this using the shell commands. New question about doing this here: stackoverflow.com/questions/1151897/…
-
caf almost 15 yearsping does use ICMP, but standard UNIX traceroute actually uses UDP by default (although it can be told to use ICMP instead). You don't need UDP echoes, because a closed port should elict an ICMP "Destination Unreachable" with a code of 0x03 ("Port Unreachable").
-
Glenn Maynard almost 15 yearsUDP traceroute is every bit as standard as ICMP. Just like ICMP, it's a natural side-effect of the standard TTL field. Ping is trickier--many secured systems simply discard packets to unopened ports, and if it's coincidentally an open port--you can't guarantee it isn't--then it probably won't work.
-
Hussain ali over 5 yearsThanks for your post. I need help with following things. I am unable to use traceroute function. I have installed scapy v2.4 and imported this in the python program. from scapy.all import *. I also need to print the time with each hop. Can you please help with this.
-
Peilonrayz about 5 yearsBoth links are giving 404s now, making this link only answer useless.
-
Tom Greenwood over 4 yearsI can confirm that mtrpacket is great!
-
Sherd over 2 yearsThe webb library hasn't been updated in years and glaring Python3 bug hasn't been resolved, would not recommend usage in production code.
-
George Adams about 2 yearsDepending on the Python version you are using, you can pip install the specific scapy version that you need. Check this out: scapy.readthedocs.io/en/latest/installation.html