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

后端 未结 7 1674
走了就别回头了
走了就别回头了 2021-01-05 14:56

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 solutio

7条回答
  •  孤城傲影
    2021-01-05 15:47

    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
    

提交回复
热议问题