在Python中,你可以使用ping3庫來實現ping命令的功能
首先,你需要安裝ping3庫。你可以使用以下命令來安裝:
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} 毫秒內響應")
break
else:
print(f"{host} 無響應")
except exceptions.Timeout as e:
print(f"{host} 請求超時: {e}")
except PermissionError:
print("請以管理員權限運行此程序")
except Exception as e:
print(f"發生錯誤: {e}")
if __name__ == "__main__":
host = input("請輸入要ping的主機名或IP地址: ")
ping_host(host)
這個程序定義了一個名為ping_host的函數,它接受三個參數:要ping的主機名或IP地址、超時時間和ping次數。函數使用ping3庫的ping函數來發送ICMP Echo請求,并等待響應。如果收到響應,它將輸出響應時間(以毫秒為單位);如果沒有收到響應,它將輸出相應的消息。程序還處理了一些可能的異常,如請求超時和權限錯誤。
請注意,這個程序僅適用于支持ICMP協議的操作系統,如Windows和Linux。在macOS上,你可能需要安裝額外的軟件包(如ping命令)才能使用此程序。