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实现简单日志记录库glog的使用

这篇文章主要介绍了python实现简单日志记录库glog的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一、 glog的简介 g...

python 应用之Pycharm 新建模板默认添加编码格式-作者-时间等信息【推荐】

python 应用之Pycharm 新建模板默认添加编码格式-作者-时间等信息【推荐】

在pycharm使用过程中,对于每次新建文件的编码格式和关于代码编写者的一些个人信息快捷填写,方法如下: 1.打开pycharm,选择File-Settings(Ctrl + Alt +...

Python判断文件和字符串编码类型的实例

python判断文件和字符串编码类型可以用chardet工具包,可以识别大多数的编码类型。但是前几天在读取一个Windows记事本保存的txt文件时,GBK却被识别成了KOI8-R,无解...

python实现发送邮件及附件功能

python实现发送邮件及附件功能

今天给大伙说说python发送邮件,官方的多余的话自己去百度好了,还有一大堆文档说实话不到万不得已的时候一般人都不会去看,回归主题: 本人是mac如果没有按照依赖模块的请按照下面的截图安...

Python中的ctime()方法使用教程

 ctime()方法转换,因为历元到表示本地时间的字符串表示以秒为单位的时间。如果不设置秒时或None,所返回的时间的当前time()被使用。使用asctime(localti...