在Python中,您可以使用第三方庫ping3來執行ping操作
pip install ping3
安裝完成后,您可以使用以下代碼執行ping操作:
from ping3 import ping, exceptions
def ping_host(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} 毫秒內響應")
return True
else:
print(f"{host} 無響應")
except exceptions.Timeout as e:
print(f"{host} 請求超時: {e}")
except PermissionError:
print("請以管理員權限運行此腳本")
break
return False
host = "example.com"
if ping_host(host):
print(f"{host} 可達")
else:
print(f"{host} 不可達")
請將example.com替換為您要ping的主機地址。這個腳本將發送指定次數的ping請求(默認為4次),并輸出每次請求的延遲時間。如果目標主機可達,腳本將返回True,否則返回False。