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

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

創(chuàng)新互聯(lián)公司服務(wù)項(xiàng)目包括西固網(wǎng)站建設(shè)、西固網(wǎng)站制作、西固網(wǎng)頁(yè)制作以及西固網(wǎng)絡(luò)營(yíng)銷策劃等。多年來(lái),我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,西固網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到西固省份的部分城市,未來(lái)相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!

過(guò)程:

1、把需要ping的網(wǎng)段中所有ip存到數(shù)組中(我是放到數(shù)組中了,其實(shí)直接for循環(huán),一個(gè)個(gè)的也行)

2、遍歷數(shù)組,逐個(gè)ping

3、根據(jù)ping返回的字符串,判斷是否ping通

4、結(jié)果存入txt中

下面上代碼咯(其實(shí)可以簡(jiǎn)化代碼的,我這里就不簡(jiǎn)化了)

#!/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)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。

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

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

廣告

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

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