温馨提示×

利用Python发送ping请求的方法

小樊
86
2024-12-07 13:24:39
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,您可以使用ping3库来发送ping请求

pip install ping3

然后,您可以使用以下代码发送ping请求:

from ping3 import ping, exceptions

def send_ping(host, timeout=1, count=4):
    for i in range(count):
        try:
            delay = ping(host, timeout)
            if delay is not None:
                print(f"{host}{delay:.2f} 毫秒内响应")
            else:
                print(f"{host} 无响应")
        except exceptions.Timeout as e:
            print(f"{host} 请求超时: {e}")
        except PermissionError:
            print("请以管理员权限运行此脚本")
        except Exception as e:
            print(f"发送ping请求时发生错误: {e}")

if __name__ == "__main__":
    host = input("请输入要ping的主机名或IP地址: ")
    send_ping(host)

这个脚本定义了一个名为send_ping的函数,该函数接受一个主机名或IP地址作为参数,并发送指定次数的ping请求。您可以根据需要调整超时和请求次数。运行此脚本后,它将提示您输入要ping的主机名或IP地址,然后显示响应时间或相应的错误消息。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:ajax发送请求的方法是什么

0