Python检查ping终端的方法
Python  /  管理员 发布于 7年前   147
菜鸟一枚,写着试了试,虽说有点杂乱,但还是能用,我是在linux下运行的
大致说下过程:
1、把需要ping的网段中所有ip存到数组中(我是放到数组中了,其实直接for循环,一个个的也行)
2、遍历数组,逐个ping
3、根据ping返回的字符串,判断是否ping通
4、结果存入txt中
下面上代码咯(其实可以简化代码的,我这里就不简化了)
#!/usr/bin/env python# coding: utf8 import timeimport subprocessimport codecsimport osimport re # telnet hostdef pingComputer(host, statusFile):status1 = 'ping success'status2 = 'ping faild'errorStr = 'Destination'for ipAdd in host:print ("get: " +ipAdd + " status")# get now timenowTime = 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 ifif errorStr in line:writeToText(nowTime, ipAdd, status2, statusFile)else:writeToText(nowTime, ipAdd, status1, statusFile) # write status information to txtdef 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 existsdef judgeFile(statusFile):if os.path.exists(statusFile):return '0'else:return '1'if __name__ == "__main__":IpFirst = '192.168.1.'# ip:1~254host = []for j in range(254): host.append(IpFirst + str(j + 1))# write filestatusFile = '/root/UpStatus.txt'pingComputer(host, statusFile)
就是一台一台的ping,判断,有点慢!
以上这篇Python检查ping终端的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号