zabbix 自动发现 python

简介:

  1. disk name

1
2
3
4
5
6
7
8
9
10
11
12
13
#/usr/bin/python
#This script is used to discovery disk on the server
import  subprocess
import  json
args = "cat /proc/diskstats |grep -E '\ssd[a-z]\s|\sxvd[a-z]\s|\svd[a-z]\s'|awk '{print $3}'|sort|uniq 2>/dev/null"
t = subprocess.Popen(args,shell = True ,stdout = subprocess.PIPE).communicate()[ 0 ]
  
disks = []
  
for  disk  in  t.split( '\n' ):
     if  len (disk) ! =  0 :
        disks.append({ '{#DISK_NAME}' :disk})
print  json.dumps({ 'data' :disks},indent = 4 ,separators = ( ',' , ':' ))


2.监控网站访问时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import  os,sys
import  time
import  sys
import  pycurl
import  json
urllist = [ 'a.com' , 'b.com' , 'c.com' , 'd.com' , 'e.com' ]
class  Test:
     def  __init__( self ):
         self .contents  =  ''
     def  callback( self ,curl):
         self .contents  =  self .contents  +  curl
def  test_gzip(url):
     data  =  {}
     =  Test()
     =  pycurl.Curl()
     c.setopt(pycurl.WRITEFUNCTION,t.callback)
     c.setopt(pycurl.ENCODING,  'gzip' )
     c.setopt(pycurl.URL,url)
     c.perform()
     data[ 'HTTP_CODE' ] = c.getinfo(c.HTTP_CODE)
     data[ 'NAMELOOKUP_TIME' ] = (c.getinfo(c.NAMELOOKUP_TIME)) * 1000
     data[ 'CONNECT_TIME' ] = (c.getinfo(c.CONNECT_TIME)) * 1000
     data[ 'PRETRANSFER_TIME' ] = (c.getinfo(c.PRETRANSFER_TIME)) * 1000
     data[ 'SPEED_DOWNLOAD' ] = c.getinfo(c.SPEED_DOWNLOAD)
     return  data
def  web_name_discovery():
     web_list = []
     web_dict = { "data" : None }
     for  url  in  urllist:
         url_dict = {}
         url_dict[ "{#NAME}" ] = url
         web_list.append(url_dict)
     web_dict[ "data" ] = web_list
     jsonStr  =  json.dumps(web_dict, sort_keys = True , indent = 4 )
     return  jsonStr
def  get_web_status():
     data = test_gzip(sys.argv[ 2 ])
     return  data[sys.argv[ 3 ]]
if  __name__  = =  '__main__' :
     if  sys.argv[ 1 = =  "web_name_discovery" :
         print  web_name_discovery()
     elif  sys.argv[ 1 = =  "get_web_status" :
         print  get_web_status()


3.输出指定目录tomcat名称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#/usr/bin/python
#This script is used to discovery disk on the server
import  subprocess
import  os
import  socket
import  json
import  glob
  
java_names_file = 'java_names.txt'
javas = []
if  os.path.isfile(java_names_file):
#   print 'java_names_file exists!'
#####
##### here should use % (java_names_file) instead of using the python variable java_names_file directly inside the '''   ''' quotes
#####
  
    args = '''awk -F':' '{print $1':'$2}' %s'''   %  (java_names_file)
    t = subprocess.Popen(args,shell = True ,stdout = subprocess.PIPE).communicate()[ 0 ]
elif  glob.glob( '/xx/xx/*_tomcat' and  not  os.path.isdir( '/opt/logs/logstash' and  not  os.path.isdir( '/opt/app/elasticsearch/config' ):
    t = subprocess.Popen( 'cd /xx/xx && ls *_tomcat|grep _tomcat' ,shell = True ,stdout = subprocess.PIPE)
   
for  java  in  t.stdout.readlines():
     if  len (java) ! =  0 :
        javas.append({ '{#JAVA_NAME}' :java.strip( '\n' ).strip( ':' )})
print  json.dumps({ 'data' :javas},indent = 4 ,separators = ( ',' , ':' ))


4.port

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/python
#coding=utf-8
import  commands
import  os,sys   
##########返回命令执行结果
def  getComStr(comand):
     try :
         stat, proStr  =  commands.getstatusoutput(comand)
     except :
         print  "command %s execute failed, exit"  %  comand
     #将字符串转化成列表
     #proList = proStr.split("\n")
     return  proStr
    
##########获取系统服务名称和监听端口
def  filterList():
     tmpStr  =  getComStr( "netstat -tpln" )
     tmpList  =  tmpStr.split( "\n" )
     del  tmpList[ 0 : 2 ]
     newList  =  []
     for  in  tmpList:
         val  =  i.split()
         del  val[ 0 : 3 ]
         del  val[ 1 : 3 ]
         #提取端口号
         valTmp  =  val[ 0 ].split( ":" )
         val[ 0 =  valTmp[ 1 ]
         #提取服务名称
         valTmp  =  val[ 1 ].split( "/" )
         val[ 1 =  valTmp[ - 1 ]
         if  val[ 1 ] ! =  '-'  and  val  not  in  newList:
             newList.append(val)
     return  newList
    
def  main():
     netInfo  =  filterList()
     #格式化成适合zabbix lld的json数据
     json_data  =  "{\n"  +  "\t"  +  '"data":['  +  "\n"
     #print netInfo
     for  net  in  netInfo:
         if  net ! =  netInfo[ - 1 ]:
            json_data  =  json_data  +  "\t\t"  +  "{"  +  "\n"  +  "\t\t\t"  +  '"{#PPORT}":"'  +  str (net[ 0 ])  +  "\ ",\n"  +  "\t\t\t"  +  '"{#PNAME}":"'  +  str (net[ 1 ])  +  "\ "},\n"
         else :
            json_data  =  json_data  +  "\t\t"  +  "{"  +  "\n"  +  "\t\t\t"  +  '"{#PPORT}":"'  +  str (net[ 0 ])  +  "\ ",\n"  +  "\t\t\t"  +  '"{#PNAME}":"'  +  str (net[ 1 ])  +  "\ "}]}"
     print  json_data
    
if  __name__  = =  "__main__" :
     main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
[root@xx ~] # /usr/bin/python  /usr/local/zabbix/bin/ports.py
{
     "data" :[
         {
             "{#PPORT}" : "10050" ,
             "{#PNAME}" : "zabbix_agentd" },
         {
             "{#PPORT}" : "10051" ,
             "{#PNAME}" : "zabbix_server" },
         {
             "{#PPORT}" : "9000" ,
             "{#PNAME}" : "php-fpm" },
         {
             "{#PPORT}" : "27017" ,
             "{#PNAME}" : "mongod" },
         {
             "{#PPORT}" : "3306" ,
             "{#PNAME}" : "mysqld" },
         {
             "{#PPORT}" : "6379" ,
             "{#PNAME}" : "redis-server" },
         {
             "{#PPORT}" : "111" ,
             "{#PNAME}" : "rpcbind" },
         {
             "{#PPORT}" : "80" ,
             "{#PNAME}" : "nginx" },
         {
             "{#PPORT}" : "8080" ,
             "{#PNAME}" : "java" },
         {
             "{#PPORT}" : "43088" ,
             "{#PNAME}" : "rpc.statd" },
         {
             "{#PPORT}" : "22" ,
             "{#PNAME}" : "sshd" },
         {
             "{#PPORT}" : "631" ,
             "{#PNAME}" : "cupsd" },
         {
             "{#PPORT}" : "3000" ,
             "{#PNAME}" : "grafana-serve" },
         {
             "{#PPORT}" : "4505" ,
             "{#PNAME}" : "python2.6" },
         {
             "{#PPORT}" : "25" ,
             "{#PNAME}" : "master" },
         {
             "{#PPORT}" : "4506" ,
             "{#PNAME}" : "python2.6" },
         {
             "{#PPORT}" : "20474" ,
             "{#PNAME}" : "java" }]}



5.监控api返回的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import  subprocess
import  json
args  =  '''awk -F' ' '{print $1}' /usr/local/zabbix/scripts/warn.txt|grep -v "#"'''
=  subprocess.Popen(args, shell = True , stdout = subprocess.PIPE).communicate()[ 0 ]
lwarns  =  []
 
for  mongo  in  t.split( '\n' ):
     if  len (mongo) ! =  0 :
         lwarns.append({ '{#WARN_HOST}' : mongo})
print  json.dumps({ 'data' : lwarns}, indent = 4 , separators = ( ',' ':' ))
 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import  urllib2,sys
import  json
if  len (sys.argv)  = =  2 :
     argv1  =  sys.argv[ 1 ]
def  http_get():
     url  =  argv1   # 页面的地址
     response  =  urllib2.urlopen(url)   # 调用urllib2向服务器发送get请求
     return  response.read()   # 获取服务器返回的页面信息
ret  =  http_get()
retj = json.loads(ret)
if  retj[ 'action' = =  "NONE" :
     print  0
elif  retj[ 'action' = =  "DEBUG" :
     print  0
else :
     print  1


6.tcp 应用端口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
[root@xx zabbix_agentd.conf.d] # cat tcp_services.conf 
UserParameter = tcp_services,  / usr / bin / python  / usr / local / zabbix / bin / tcp_services.py
 
#/usr/bin/python
#This script is used to discovery disk on the server
import  subprocess
import  os
import  socket
import  json
import  glob
  
java_names_file = 'java_names.txt'
javas = []
if  os.path.isfile(java_names_file):
#   print 'java_names_file exists!'
#####
##### here should use % (java_names_file) instead of using the python variable java_names_file directly inside the '''   ''' quotes
#####
  
    args = '''awk -F':' '{print $1':'$2}' %s'''   %  (java_names_file)
    t = subprocess.Popen(args,shell = True ,stdout = subprocess.PIPE).communicate()[ 0 ]
elif  glob.glob( '/xx/xx/*_tomcat' and  not  os.path.isdir( '/opt/logs/logstash' and  not  os.path.isdir( '/opt/app/elasticsearch/config' ):
    t = subprocess.Popen( 'cd /xx/xx && ls *|grep _tomcat' ,shell = True ,stdout = subprocess.PIPE)
   
for  java  in  t.stdout.readlines():
     if  len (java) ! =  0 :
        S = java.strip( '\n' ).strip( ':' )
        args = "cat /xx/xx/%s/conf/server.xml|grep port|sed -n '2p'|awk '{print $2}'|awk -F '=' '{print $2}'|tr -d '\"'"  %  S
        port = subprocess.Popen(args,shell = True ,stdout = subprocess.PIPE).communicate()[ 0 ].strip( '\n' )
        STR1 = { '{#PROCNAME}' :S}
        STR2 = { '{#PORT}' :port}
        STR3 = dict (STR1,  * * STR2)
        javas.append(STR3)
print  json.dumps({ 'data' :javas},indent = 4 ,separators = ( ',' , ':' ))
 
[root@xx zabbix_agentd.conf.d] # /usr/bin/python /usr/local/zabbix/bin/tcp_services.py
{
     "data" :[
         {
             "{#PORT}" : "80" ,
             "{#PROCNAME}" : "dubbo_tomcat"
         }
     ]
}



本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/1969150,如需转载请自行联系原作者

相关文章
|
9月前
|
JSON 监控 前端开发
python对接API二次开发高级实战案例解析:Zabbix API封装类实现获取认证密钥、所有主机组、所有主机、所有监控项和历史数据
python对接API二次开发高级实战案例解析:Zabbix API封装类实现获取认证密钥、所有主机组、所有主机、所有监控项和历史数据
298 0
|
7月前
|
监控 安全 Ubuntu
用python部署zabbix
用python部署zabbix
60 1
|
Python
使用Python自动发送邮件
使用Python自动发送邮件
298 0
使用Python自动发送邮件
|
XML JSON 自然语言处理
python接口自动化(三十三)-python自动发邮件总结及实例说明番外篇——下(详解)
发邮件前我们需要了解的是邮件是怎么一个形式去发送到对方手上的,通俗点来说就是你写好一封信,然后装进信封,写上地址,贴上邮票,然后就近找个邮局,把信仍进去,其他的就不关心了,只是关心时间,而电子邮件不像日常发送邮件的按天算,时间都是按秒算的。
176 0
python接口自动化(三十三)-python自动发邮件总结及实例说明番外篇——下(详解)
|
数据挖掘 Python
用Python学线性代数:自动拟合数据分布
用Python学线性代数:自动拟合数据分布
用Python学线性代数:自动拟合数据分布
|
存储 Python
【Pyqt实战】1-100算式练习题自动生成器(含UI界面,python代码),可自行选择参数
【Pyqt实战】1-100算式练习题自动生成器(含UI界面,python代码),可自行选择参数
【Pyqt实战】1-100算式练习题自动生成器(含UI界面,python代码),可自行选择参数
|
数据安全/隐私保护 Python
|
Python
python做的快手自动评论工具 源码开源
可以自动打开快手 评论
176 0

推荐镜像

更多