首页 > 数据库技术 > 详细

zabbix-ping脚本自定义粒度,数据存入数据库,可供其他脚本使用

时间:2021-05-08 00:36:44      阅读:16      评论:0      收藏:0      [点我收藏+]

 环境

  python3.6,pymysql库,mysql

zabbixping脚本

 1 #!/usr/bin/env python3
 2 #-*-coding:utf-8-*-
 3 #----------------------------------------------------------zabbixping脚本----------------------------------------------------
 4 import pymysql,time,argparse,subprocess,os,logging
 5 #路径拼接
 6 dir_path = os.path.dirname(os.path.abspath(__file__))
 7 log_name = dir_path + /log/ + time.strftime(%Y-%m-%d,time.localtime()) + .log
 8 #logger模块
 9 def logger():
10     logger = logging.getLogger()
11     fh = logging.FileHandler(log_name)
12     formater = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
13     fh.setFormatter(formater)
14     logger.setLevel(logging.DEBUG)
15     logger.addHandler(fh)
16     return logger
17 logger = logger()
18 
19 def dark_zabbix(ip,item,i):
20     res_ret = 0
21     pkloss_ret = 0
22     packet_count= int(20/i)
23     cmd = dir_path + /pingsql.py -t %s -i %s%(ip,i)
24     #创建数据库连接
25     conn = pymysql.connect(host=127.0.0.1,port = 3306,user = root,passwd = darkcs, db=pingvalues,charset=utf8)
26     coursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 
27     #根据ipaddress分组,依据自增列排倒序,取最后一行数据
28     coursor.execute(select time  from zabbixvalue where ipaddress like %s order by nid  desc limit 1;,ip)
29     now_time = int(time.time())
30     #判断最新数据时间与当前时间间隔是否超过1分钟,新建item或防止系统重启后台程序异常等
31     try:
32         ctime = (coursor.fetchone()[time])
33         if now_time - ctime > 60:
34             raise Exception(dberror)
35     except Exception as a:
36         #调用pingsql脚本开始进行探测并写入数据库
37         subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
38         logger.debug(初始化%s%ip)
39         return(res_ret)
40     #根据所设置的粒度取相应的数据
41     coursor.execute(select res,pkloss,ipaddress,time  from zabbixvalue where ipaddress like %s order by nid  desc limit %s;,(ip,packet_count))
42     ret = coursor.fetchall()
43     #初始阶段数据库数据不足以计算结果
44     if len(ret) <packet_count:
45         return(res_ret)
46     else:
47         for x in ret:
48             res_ret+=x[res]
49             pkloss_ret+=x[pkloss]
50     #计算时延和丢包率
51     if item ==restime:
52         return  (round(float(res_ret/packet_count),2))
53     if item == pkloss:
54         return  (round(float(pkloss_ret/packet_count*100),2))
55 
56 if __name__  == "__main__":
57     parser = argparse.ArgumentParser(description=icmp for monitor)
58     parser.add_argument(-t,action = store,dest=tip)
59     parser.add_argument(-i,action=store,dest=interval,default=1)
60     parser.add_argument(-I,action=store,dest=item)
61     args= parser.parse_args()
62     ip = args.tip
63     i = args.interval
64     item = args.item
65     print(dark_zabbix(ip,item,i))

 

 

 

pingmysql脚本

 1 #!/usr/bin/env python3
 2 #-*-coding:utf-8-*-
 3 # --------------------------------------------获取ping结果并写入数据库---------------------------------------------------
 4 
 5 import subprocess,re,time,pymysql,argparse
 6 
 7 
 8 def value(i,ipaddress):
 9     cmd = ping  -c 1 -W 1 %s%ipaddress11     i = float(i)
12     #while循环,根据粒度决定多久循环执行一次
13     while True:
14         #调用ping函数获取时延和丢包结果
15         res,pkloss = ping(cmd)
16         t_time = int(time.time())
17         #调用mysql函数,将结果写入数据库
18         mysql(res,pkloss,ipaddress,t_time)
19         time.sleep(i)
20     return
21 
22 def ping(cmd):
23     pkloss = 0
24     ret = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0].decode(utf8)
25     try:
26         ret =re.findall(\d+\.?\d* ,(re.findall(time=\d+\.?\d*,ret)[0]))[0]
27         return(ret,pkloss)
28     except Exception as a :
29         ret = 0
30         pkloss = 1
31         return(ret,pkloss)
32 def mysql(res,pkloss,ipaddress,t_time):
33     #2天前的时间戳
34     ctime = t_time - 86400*2
35     conn = pymysql.connect(host = 127.0.0.1,port = 3306,user = root,passwd = darkcs, db=pingvalues,charset=utf8)
36     coursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
37     #clear历史数据
38     coursor.execute(delete from zabbixvalue where time<%s;,ctime)
39     coursor.execute(insert into zabbixvalue(res,pkloss,ipaddress,time) values(%s,%s,%s,%s),(res,pkloss,ipaddress,t_time))
40     conn.commit()
41 
42 if __name__  == "__main__":
43     parser = argparse.ArgumentParser(description=icmp for monitor)
44     parser.add_argument(-t,action = store,dest=tip)
45     parser.add_argument(-i,action=store,dest=interval)
46     args= parser.parse_args()
47     ip = args.tip
48     i = args.interval
49     print(type(i),type(ip))
50     value(i,ip)
51     

 

 

 sql

create database pingvalues default charset utf8; 
create table zabbixvalue(nid int not null auto_increment primary key, num int,res varchar(64),pkloss varchar(64), ipaddress varchar(64),time varchar(64)) engine=innodb default charset=utf8;

 

创建log文件夹并赋权限

mkdir log
chown -R zabbix:zabbix log/

定义zabbix配置文件

UserParameter=dark_ping_restime[*],/etc/zabbix/dark/zabbixping.py     -t $1 -I restime
UserParameter=dark_ping_pkloss[*],/etc/zabbix/dark/zabbixping.py     -t $1 -I pkloss

添加Item略

zabbix-ping脚本自定义粒度,数据存入数据库,可供其他脚本使用

原文:https://www.cnblogs.com/darkchen/p/14735557.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!