我有以下Python代码块,可用于Ping多个地址
import subprocess as s
import tkinter as tk
from tkinter import *
IPT.title("IP Ping Test Tool")
canvas_IPT = Canvas(IPT, width=401, height=551)
canvas_IPT.pack()
Output_IP_Address_AN = Output_IP_Address[10]
IPT_Display_AN = Label(IPT, text=Output_IP_Address_AN, anchor=W)
IPT_Display_AN_Window = canvas_IPT.create_window(150, 235, anchor = 'sw', window = IPT_Display_AN)
def IPT_Test():
print("Test Initiated")
AN_Sel_State = var4.get()
if (AN_Sel_State == 1):
if(s.call(["ping", Output_IP_Address_AN])==0):
print("AvI Navi 'Ping' Sucessful")
IPT_Display_AN = Label(IPT, text=(Output_IP_Address_AN, "Ok"),fg='green', anchor=W)
IPT_Display_AN_Window = canvas_IPT.create_window(150, 235, anchor = 'sw', window = IPT_Display_AN)
else:
print("Avi Navi 'Ping' NOT Sucessful")
IPT_Display_AN = Label(IPT, text=(Output_IP_Address_AN, "Failed"),fg='red', anchor=W)
IPT_Display_AN_Window = canvas_IPT.create_window(150, 235, anchor = 'sw', window = IPT_Display_AN)
IPT_Display_AN = Label(IPT, text=Output_IP_Address_AN, anchor=W)
IPT_Display_AN_Window = canvas_IPT.create_window(150, 235, anchor = 'sw', window = IPT_Display_AN)
var4 = IntVar()
IPT_Test_AN = Checkbutton(IPT, text = "AVI/NAVI", justify=LEFT,width=15, indicatoron=0,
variable = var4, command=AN_Sel)
IPT_Test_AN_Window = canvas_IPT.create_window(20, 240, anchor = 'sw', window = IPT_Test_AN)
IPTest_Button = tk.Button(IPT, text = 'TEST', command = IPT_Test, background ="#01AEAC", width=20, height=3,)
这在接收到数据包数据(成功)的情况下按预期工作,并且在“请求超时”(不成功)时也工作,但是在“主机不可访问”时返回成功。
对此进行了一些研究,我相信即使ping并没有成功,“ Host Unreachable”也将返回== 0(仍然无法真正理解为什么)
如果是这种情况,当我的应用程序具有与成功的Ping相同的退出状态时,如何排除“ Host Unreachable”无法成功显示给我的应用程序?
答案 0 :(得分:0)
我不确定为什么在您的本地发生这种情况,我在本地进行测试,当我有以下代码时,它对我有用:
...
if(s.call(["ping", "-c", "1", "-W", "4", Output_IP_Address_AN])==0):
print("AvI Navi 'Ping' Sucessful")
...
我让ping发送1个数据包,超时时间为4秒。
在本地,我运行以下命令来模拟主机不可达的情况:
sudo ip route add unreachable 1.0.0.3
然后使用上面的更改运行代码, 并且打印不成功。当Output_IP_Address_AN设置为1.0.0.3
答案 1 :(得分:0)
由于PING请求收到的回复为:
来自xx.xx.xx.xx的答复:无法访问目标主机
从技术上讲,这仍然是答复。
因此,请尝试解析控制台输出,这可能会达到您的目的,如下所示:
ping -c 1 -w 4 ip_addr | findstr /i "TTL"
这里有一个类似的问题: Destination Host unreachable does not result in an errorlevel 1