disk name
#/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.监控网站访问时间
#!/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 = {}
t = Test()
c = 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名称
#/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
#!/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 i 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()
[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返回的值
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import json
args = '''awk -F' ' '{print $1}' /usr/local/zabbix/scripts/warn.txt|grep -v "#"'''
t = 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 应用端口
[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"
}
]
}