筆者發現
ping = os.system("ping " + "192.168.20.1")
如果ping同網域,ping 192.168.20.3
<ps. 192.168.29.3 是沒有人取得, win 7:192.168.20.14>
ping 同網段且沒人取得的IP,過程會ping不到,但回傳會給0 ,會造成誤判斷,但不同網域就不會有這問題
前幾個例子是跨往網域,就不必修改,但同網域問題,還是要解決
所以寫下這個範例,在同網段且沒人取得的IP,回傳值都是正確
就叫這專案就pingdemo ,code如下
重點:
1.會判斷你輸入ipv4格制正不正確
2.在同網段且沒人取得的IP,去ping,回傳值都是正確
3.當有ping loss,它會記錄起來,並產生檔案
4.當有500個錯誤,會停執行
5. Linux 和windows 都可以run
from subprocess import Popen,PIPE import platform import time import re num = 3 wait = 500 def ipFormatChk(ip_str): pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" if re.match(pattern, ip_str): print("ip format is correct\n") return True else: print("ip format is error\n") return False check=False while(check == False): host = input("Enter dut IP:") check=ipFormatChk(str(host)) #print(check) print("\n") con1=True FA=0 times=1 while(con1== True): fo = open('ping_loss.txt', 'a') ping = Popen("ping "+ ("-n " if platform.system().lower()=="windows" else "-c ")+ "{} -w {} {}".format(num, wait, str(host)), stdout=PIPE, stderr=PIPE) ## if you don't want it to print it out exit_code = ping.wait() if exit_code != 0: print("ping",host) fo.write("ping " + str(host) + "\n") print("result: FAIL.") fo.write("result: FAIL."+"\n") localtime = time.asctime(time.localtime(time.time())) fo.write("time : " + str(localtime) + "\n\n") FA = FA + 1 if FA == 500: con1 = False else: print("ping",host) print("result:success.") fo.close() print("\ntimes",times) print("FAIL",FA) times=times+1 print("\n") fo = open('ping_loss.txt', 'a') fo.write("times : " + str(times-1)+"\n") fo.write("FAIL : " + str(FA) + "\n\n")
全站熱搜
留言列表