Python中怎么對ping終端進行檢查-創(chuàng)新互聯(lián)

Python中怎么對ping終端進行檢查,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

創(chuàng)新互聯(lián)公司服務項目包括西固網(wǎng)站建設、西固網(wǎng)站制作、西固網(wǎng)頁制作以及西固網(wǎng)絡營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關系等,向廣大中小型企業(yè)、政府機構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,西固網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟效益。目前,我們服務的客戶以成都為中心已經(jīng)輻射到西固省份的部分城市,未來相信會繼續(xù)擴大服務區(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)容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。

網(wǎng)站名稱:Python中怎么對ping終端進行檢查-創(chuàng)新互聯(lián)
標題URL:http://muchs.cn/article44/cessee.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站動態(tài)網(wǎng)站、定制開發(fā)、域名注冊、服務器托管、做網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名