Python检查ping终端的方法

yipeiwu_com5年前Python基础

菜鸟一枚,写着试了试,虽说有点杂乱,但还是能用,我是在linux下运行的

大致说下过程:

1、把需要ping的网段中所有ip存到数组中(我是放到数组中了,其实直接for循环,一个个的也行)

2、遍历数组,逐个ping

3、根据ping返回的字符串,判断是否ping通

4、结果存入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)

就是一台一台的ping,判断,有点慢!

以上这篇Python检查ping终端的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python+opencv+caffe+摄像头做目标检测的实例代码

python+opencv+caffe+摄像头做目标检测的实例代码

首先之前已经成功的使用Python做图像的目标检测,这回因为项目最终是需要用摄像头的, 所以实现摄像头获取图像,并且用Python调用CAFFE接口来实现目标识别 首先是摄像头请选择支持...

Python程序语言快速上手教程

Python程序语言快速上手教程

本来打算从网上找一篇入门教程,但因为Python很少是程序员的第一次接触程序所学的语言,所以网上现有的教程多不是很基础,还是决定自己写下这些。 如果没有程序基础的话,可能会觉得本文涵盖的...

PyQt5 QTable插入图片并动态更新的实例

PyQt5 QTable插入图片并动态更新的实例

方式一:图片+文字 row = 0 # 行号 col = 1 # 列号 icon = QTableWidgetItem(QIcon("../image/a.png"), "Waiti...

解决pandas 作图无法显示中文的问题

解决pandas 作图无法显示中文的问题

最近开始使用 pandas 处理可视化数据,挖掘信息。但是在作图时遇到,无法显示中文的问题。 下面这段代码是统计 fujian1.csv 文件中 City 所在列中各个城市出现次数的代码...

在python的类中动态添加属性与生成对象

本文将通过一下几个方面来一一进行解决       1、程序的主要功能       2...