菜鳥一枚,寫著試了試,雖說有點雜亂,但還是能用,我是在linux下運行的
大致說下過程:
1、把需要ping的網段中所有ip存到數組中(我是放到數組中了,其實直接for循環,一個個的也行)
2、遍歷數組,逐個ping
3、根據ping返回的字符串,判斷是否ping通
4、結果存入txt中
下面上代碼咯(其實可以簡化代碼的,我這里就不簡化了)
#!/usr/bin/env python# coding: utf8 import timeimport subprocessimport codecsimport osimport re # telnet hostdef pingComputer(host, statusFile): status1 = 'ping success' status2 = 'ping faild' errorStr = 'Destination' for ipAdd in host: print ("get: " +ipAdd + " status") # get now time nowTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) p = os.popen("ping -q -c 2 -r " + ipAdd) line = p.read() # judge errorstr in line if if errorStr in line: writeToText(nowTime, ipAdd, status2, statusFile) else: writeToText(nowTime, ipAdd, status1, statusFile) # write status information to txtdef writeToText(nowTime, ipAdd, status, statusFile): s_text = 'TIME:' + nowTime + '/t' + 'IP:' + ipAdd + '/t' + 'STATUS:' + status + '/r/n' if '0' == judgeFile(statusFile): with open(statusFile, 'a') as f: f.write(s_text) f.close() if '1' == judgeFile(statusFile): with open(statusFile, 'w') as f: f.write(s_text) f.close() # Determine whether statusFile exists # 0: exists# 1: no existsdef judgeFile(statusFile): if os.path.exists(statusFile): return '0' else: return '1' if __name__ == "__main__": IpFirst = '192.168.1.' # ip:1~254 host = [] for j in range(254): host.append(IpFirst + str(j + 1)) # write file statusFile = '/root/UpStatus.txt' pingComputer(host, statusFile)就是一臺一臺的ping,判斷,有點慢!
以上這篇Python檢查ping終端的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答