Ping值监测小工具(比较实用 已测试)

  • A+
所属分类:python实战
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import os
  4. import time
  5. import commands
  6. import sys
  7. class Pinger():
  8.     STYLE = {
  9.         'fore': {
  10.             'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
  11.             'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37,
  12.         },
  13.         'back': {
  14.             'black': 40, 'red': 41, 'green': 42, 'yellow': 43,
  15.             'blue': 44, 'purple': 45, 'cyan': 46, 'white': 47,
  16.         },
  17.         'mode': {
  18.             'bold': 1, 'underline': 4, 'blink': 5, 'invert': 7,
  19.         },
  20.         'default': {
  21.             'end': 0,
  22.         }
  23.     }
  24.     def __init__(self, host):
  25.         self.start_time = time.localtime(time.time())
  26.         self.start_time_m = time.time()
  27.         self.data = dict()
  28.         self.host = host
  29.         self.midnight_zero = list()
  30.         self.midnight_non_zero = list()
  31.         self.morning_zero = list()
  32.         self.morning_non_zero = list()
  33.         self.afternoon_zero = list()
  34.         self.afternoon_non_zero = list()
  35.         self.night_zero = list()
  36.         self.night_non_zero = list()
  37.     def ping(self):
  38.         cmd = "ping "+ self.host + " -c1 -W 1"
  39.         result = commands.getoutput(cmd)
  40.         result = result.split()
  41.         result = result[-2].split("/")[0]
  42.         if result.isalpha():
  43.             result =0
  44.         return float(result)
  45.     def use_style(self,stringmode='', fore='', back=''):
  46.         mode = '%s' % self.STYLE['mode'][modeif self.STYLE['mode'].has_key(modeelse ''
  47.         fore = '%s' % self.STYLE['fore'][fore] if self.STYLE['fore'].has_key(fore) else ''
  48.         back = '%s' % self.STYLE['back'][back] if self.STYLE['back'].has_key(back) else ''
  49.         style = ';'.join([s for s in [mode, fore, back] if s])
  50.         style = '\033[%sm' % style if style else ''
  51.         end = '\033[%sm' % self.STYLE['default']['end'] if style else ''
  52.         return '%s%s%s' % (style, string, end)
  53.     def red(self,str):
  54.         return self.use_style(str,fore="red")
  55.     def blue(self,str):
  56.         return self.use_style(str,fore="blue")
  57.     def cyan(self,str):
  58.         return self.use_style(str,fore="cyan")
  59.     def yellow(self,str):
  60.         return self.use_style(str,fore="yellow")
  61.     def green(self,str):
  62.         return self.use_style(str,fore="green")
  63.     def purple(self,str):
  64.         return self.use_style(str,fore="purple")
  65.     def colored(self,latency):
  66.         if latency == 0:
  67.             return self.red(str(round(latency,2)) + " ms")
  68.         elif(0<latency < 100):
  69.             return self.green(str(round(latency,2)) + " ms")
  70.         elif latency < 170:
  71.             return self.yellow(str(round(latency,2)) + " ms")
  72.         else:
  73.             return self.red(str(round(latency,2)) + " ms")
  74.     def start(self):
  75.         current_time = time.localtime(time.time())
  76.         i=1
  77.         while(time.time() - self.start_time_m <= 86400):
  78.             latency=self.ping()
  79.             current_time = time.localtime(time.time())
  80.             self.data[i] = {"year":  current_time[0], \
  81.                             "month": current_time[1], \
  82.                             "day" :  current_time[2], \
  83.                             "hour" : current_time[3], \
  84.                             "minute":current_time[4], \
  85.                             "second":current_time[5],\
  86.                             "latency": latency}
  87.             i = i + 1
  88.             self.print_graph()
  89.             self.data.clear()
  90.             if(latency != 0.0):
  91.                 time.sleep(1)
  92.     def is_night(self,d):
  93.         if  18 <= d["hour"] <= 23:
  94.             return True
  95.         else:
  96.             return False
  97.     def is_morning(self,d):
  98.         if 6 <= d["hour"] <= 12:
  99.             return True
  100.         else:
  101.             return False
  102.     def is_mid_night(self,d):
  103.         if 0 < d["hour"] < 6:
  104.             return True
  105.         else:
  106.             return False
  107.     def is_afternoon(self,d):
  108.         if 12 < d["hour"] < 18:
  109.             return True
  110.         else:
  111.             return False
  112.     def lost_percentage(self,zero,non_zero):
  113.         sum = len(zero) + len(non_zero)
  114.         if sum == 0:
  115.             return self.red(str(0) + " %")
  116.         else:
  117.             percentage = 100 * len(zero) / sum
  118.         if percentage <5:
  119.             return self.green(str(int(percentage)) + " %")
  120.         elif percentage < 10:
  121.             return self.yellow(str(int(percentage)) + " %")
  122.         else:
  123.             return self.red(str(int(percentage)) + " %")
  124.     def print_graph(self):
  125.         os.system("clear")
  126.         spend_time = (time.time() - self.start_time_m)
  127.         for i in self.data.keys():
  128.             x = self.data[i]
  129.             latency = x["latency"]
  130.             total_count = self.data.keys()[-1]
  131.             if(self.is_mid_night(x)):
  132.                 if latency == 0:
  133.                     self.midnight_zero.append(latency)
  134.                 else:
  135.                     self.midnight_non_zero.append(latency)
  136.             elif(self.is_morning(x)):
  137.                 if latency == 0:
  138.                     self.morning_zero.append(latency)
  139.                 else:
  140.                     self.morning_non_zero.append(latency)
  141.             elif(self.is_afternoon(x)):
  142.                 if latency == 0:
  143.                     self.afternoon_zero.append(latency)
  144.                 else:
  145.                     self.afternoon_non_zero.append(latency)
  146.             elif(self.is_night(x)):
  147.                 if latency == 0:
  148.                     self.night_zero.append(latency)
  149.                 else:
  150.                     self.night_non_zero.append(latency)
  151.             else:
  152.                 print("Error :", x)
  153.         total_non_zero = self.morning_non_zero + self.midnight_non_zero + self.afternoon_non_zero+self.night_non_zero
  154.         total_zero_list = self.morning_zero + self.midnight_zero + self.afternoon_zero+self.night_zero
  155.         total_zero = len(total_zero_list)
  156.         if(total_count - total_zero == 0):
  157.             total_average = 0
  158.         else:
  159.             total_average = sum(total_non_zero)/(total_count - total_zero)
  160.         if len(self.morning_non_zero) == 0:
  161.             morning_average = 0
  162.         else:
  163.             morning_average = sum(self.morning_non_zero) / len(self.morning_non_zero)
  164.         if len(self.afternoon_non_zero) == 0:
  165.             afternoon_average = 0
  166.         else:
  167.             afternoon_average = sum(self.afternoon_non_zero) / len(self.afternoon_non_zero)
  168.         if len(self.night_non_zero) == 0:
  169.             night_average = 0
  170.         else:
  171.             night_average = sum(self.night_non_zero) / len(self.night_non_zero)
  172.         if len(self.midnight_non_zero) == 0:
  173.             midnight_average = 0
  174.         else:
  175.             midnight_average = sum(self.midnight_non_zero) / len(self.midnight_non_zero)
  176.         print("-" * 53)
  177.         print("|{0:16}{1:37}{2:16}|".format("",self.cyan("服务器延迟监测脚本"),""))
  178.         print("-" * 53)
  179.         print "| {0:37}| {1:37}|".format(self.blue("上午统计"),self.blue("下午统计"))
  180.         print("{0:39}| {1:37}|".format("| 最低延迟: " + self.colored(  min(self.morning_non_zero) if len(self.morning_non_zero)!=0 else 0),"最低延迟: " + self.colored(min(self.afternoon_non_zero) if len(self.afternoon_non_zero) != 0 else 0)  )  )
  181.         print("{0:39}| {1:37}|".format("| 最高延迟: " + self.colored(max(self.morning_non_zero) if len(self.morning_non_zero)!=0 else 0),"最高延迟: " + self.colored(max(self.afternoon_non_zero) if len(self.afternoon_non_zero) != 0 else 0)))
  182.         print("{0:39}| {1:37}|".format("| 平均延迟: " + self.colored(morning_average),"平均延迟: " + self.colored(afternoon_average)))
  183.         print("{0:38}| {1:36}|".format("| 丢包率  : "+ self.lost_percentage(self.morning_zero,self.morning_non_zero),"丢包率  : " + self.lost_percentage(self.afternoon_zero,self.afternoon_non_zero)))
  184.         print("{0:39}| {1:37}|".format("| 超时次数: " + self.red(len(self.morning_zero)),"超时次数: " + self.red(len(self.afternoon_zero))))
  185.         print("{0:30}| {1:28}|".format("| 测试次数: " + str(len(self.morning_non_zero) + len(self.morning_zero)),"测试次数: " + str(len(self.afternoon_non_zero) + len(self.afternoon_zero))))
  186.         print("-" * 53)
  187.         print "| {0:37}| {1:37}|".format(self.blue("夜晚统计"), self.blue("半夜统计"))
  188.         print("{0:39}| {1:37}|".format(
  189.             "| 最低延迟: " + self.colored(min(self.night_non_zero) if len(self.night_non_zero) != 0 else 0),
  190.             "最低延迟: " + self.colored(min(self.midnight_non_zero) if len(self.midnight_non_zero) != 0 else 0)))
  191.         print("{0:39}| {1:37}|".format(
  192.             "| 最高延迟: " + self.colored(max(self.night_non_zero) if len(self.night_non_zero) != 0 else 0),
  193.             "最高延迟: " + self.colored(max(self.midnight_non_zero) if len(self.midnight_non_zero) != 0 else 0)))
  194.         print("{0:39}| {1:37}|".format("| 平均延迟: " + self.colored(night_average),
  195.                                        "平均延迟: " + self.colored(midnight_average)))
  196.         print("{0:38}| {1:36}|".format("| 丢包率  : "+ self.lost_percentage(self.night_zero,self.night_non_zero),"丢包率  : " + self.lost_percentage(self.midnight_zero,self.midnight_non_zero)))
  197.         print("{0:39}| {1:37}|".format("| 超时次数: " + self.red(len(self.night_zero)),
  198.                                        "超时次数: " + self.red(len(self.midnight_zero))))
  199.         print("{0:30}| {1:28}|".format("| 测试次数: " + str(len(self.night_non_zero) + len(self.night_zero)),
  200.                                        "测试次数: " + str(len(self.midnight_non_zero) + len(self.midnight_zero))))
  201.         print("-" * 53)
  202.         print "| {0:63}|".format(self.blue("全局统计"))
  203.         print("{0:41}{1:36}|".format("| 最低延迟: " + self.colored(min(total_non_zero) if len(total_non_zero) != 0 else 0),"丢包率    : " + self.lost_percentage(total_zero_list,total_non_zero)))
  204.         print("{0:41}{1:38}|".format("| 最高延迟: " + self.colored(max(total_non_zero) if len(total_non_zero) != 0 else 0),"总超时次数: " + self.red(total_zero)))
  205.         print("{0:41}{1:29}|".format("| 平均延迟: " + self.colored(total_average),"总测试次数: " + str(total_count)))
  206.         print("-" * 53)
  207.         print ("|{0:13}{1:30}{2:22}{3:9}|".format("", self.purple("当前测试Ping值:"), self.colored(self.data[self.data.keys()[-1]]["latency"]),""))
  208.         print("-" * 53)
  209.         print("|{0:12}{1:4}{2:2} 小时{3:2} 分钟{4:2} 秒{5:13}|".format("",self.purple("已耗时:"),int(spend_time/3600)if spend_time/3600 >=1 else 0,(int(spend_time % 3600 /60))if spend_time % 3600 /60 >= 1 else 0,int(spend_time % 3600 %60),""))
  210.         print("-" * 53)
  211. if __name__ == "__main__" :
  212.     os.system("clear")
  213.     print("服务器延迟监测脚本")
  214.     print("Made By 主机博客(zhujiboke.com)")
  215.     print("")
  216.     mytime = time.localtime(time.time())
  217.     print("当前服务器时间为: " + str(mytime[0]) + "年" + str(mytime[1]) + "月" + str(mytime[2]) +"日 "  + str(mytime[3]) + ":" + str(mytime[4]) + ":" + str(mytime[5]) )
  218.     myinput = raw_input("是否正确 (y/n): ")
  219.     if myinput == "y":
  220.         pinghost = raw_input("请输入要Ping的服务器IP/域名:")
  221.         p = Pinger(pinghost)
  222.         p.start()
  223.     else:
  224.         print("\n请将服务器时间调整正确后运行本程序!")
  225. 相关代码:
  226. https://raw.githubusercontent.com/FunctionClub/uPing/master/uping.py
  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: