当前位置: 移动技术网 > IT编程>脚本编程>Python > Python检查ping终端的方法

Python检查ping终端的方法

2019年03月20日  | 移动技术网IT编程  | 我要评论

qq游戏刷分,城固贴吧,芭比公主怀孕小游戏

菜鸟一枚,写着试了试,虽说有点杂乱,但还是能用,我是在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终端的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网