Python检查ping终端的方法
作者:Persistent_
今天小编就为大家分享一篇Python检查ping终端的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
菜鸟一枚,写着试了试,虽说有点杂乱,但还是能用,我是在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终端的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- Pycharm中安装wordcloud等库失败问题及终端通过pip安装的Python库如何添加到Pycharm解释器中(推荐)
 - Python在终端通过pip安装好包以后在Pycharm中依然无法使用的问题(三种解决方案)
 - Python终端输出彩色字符方法详解
 - python paramiko远程服务器终端操作过程解析
 - 使用python模拟命令行终端的示例
 - 在PyCharm的 Terminal(终端)切换Python版本的方法
 - python隐藏终端执行cmd命令的方法
 - 浅谈终端直接执行py文件,不需要python命令
 - 在Linux命令行终端中使用python的简单方法(推荐)
 - python如何在终端里面显示一张图片
 - 用Python编写一个基于终端的实现翻译的脚本
 - 在终端启动Python时报错的解决方案
 
