Python中怎么對ping終端進(jìn)行檢查,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
創(chuàng)新互聯(lián)公司服務(wù)項目包括西固網(wǎng)站建設(shè)、西固網(wǎng)站制作、西固網(wǎng)頁制作以及西固網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,西固網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到西固省份的部分城市,未來相信會繼續(xù)擴大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!過程:
1、把需要ping的網(wǎng)段中所有ip存到數(shù)組中(我是放到數(shù)組中了,其實直接for循環(huán),一個個的也行)
2、遍歷數(shù)組,逐個ping
3、根據(jù)ping返回的字符串,判斷是否ping通
4、結(jié)果存入txt中
下面上代碼咯(其實可以簡化代碼的,我這里就不簡化了)
#!/usr/bin/env python # coding: utf8 import time import subprocess import codecs import os import re # telnet host def 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 txt def 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 exists def 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)
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。
網(wǎng)站名稱:Python中怎么對ping終端進(jìn)行檢查-創(chuàng)新互聯(lián)
標(biāo)題URL:http://m.rwnh.cn/article44/cessee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、動態(tài)網(wǎng)站、定制開發(fā)、域名注冊、服務(wù)器托管、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)