Ping a site in Python?

前端 未结 15 2675
我寻月下人不归
我寻月下人不归 2020-11-22 09:22

How do I ping a website or IP address with Python?

15条回答
  •  礼貌的吻别
    2020-11-22 09:52

    I develop a library that I think could help you. It is called icmplib (unrelated to any other code of the same name that can be found on the Internet) and is a pure implementation of the ICMP protocol in Python.

    It is completely object oriented and has simple functions such as the classic ping, multiping and traceroute, as well as low level classes and sockets for those who want to develop applications based on the ICMP protocol.

    Here are some other highlights:

    • Can be run without root privileges.
    • You can customize many parameters such as the payload of ICMP packets and the traffic class (QoS).
    • Cross-platform: tested on Linux, macOS and Windows.
    • Fast and requires few CPU / RAM resources unlike calls made with subprocess.
    • Lightweight and does not rely on any additional dependencies.

    To install it (Python 3.6+ required):

    pip3 install icmplib
    

    Here is a simple example of the ping function:

    host = ping('1.1.1.1', count=4, interval=1, timeout=2, privileged=True)
    
    if host.is_alive:
        print(f'{host.address} is alive! avg_rtt={host.avg_rtt} ms')
    else:
        print(f'{host.address} is dead')
    

    Set the "privileged" parameter to False if you want to use the library without root privileges.

    You can find the complete documentation on the project page: https://github.com/ValentinBELYN/icmplib

    Hope you will find this library useful. Please do not hesitate to send me your comments on GitHub, suggestions for improving it, or any problems you encounter while using it.

提交回复
热议问题