一.登陆ZABBIX获取队列信息
先写一个类,实现:
1.登陆ZABBIX,获取KEY,再用这个KEY通过远程命令使用zabbix_get的方式拿到队列
2.拿到队列信息后比对ZABBIX后台数据库,获取监控项的信息,并根据队列的nextcheck信息进筛选和数据重组,此时将监控队列的监控项,PROXY,AGENT,nextcheck关联起来
chkzbqueue.py
#coding:utf-8
import requests
import json
import sys
reload(sys)
import json
import urllib2
from urllib2 import URLError
import paramiko
import time
sys.setdefaultencoding('utf-8')
class chkzbqueues:
def __init__(self):
self.url = 'http://serverip/api_jsonrpc.php'
self.header = {'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0',
"Content-Type": "application/json"}
def user_login(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "username",
"password": "password"
},
"id": 0
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
try:
result = urllib2.urlopen(request)
except URLError as e:
print ("Auth Failed, please Check your name and password:", e.code)
else:
response = json.loads(result.read())
result.close()
self.authID = response['result']
#print self.authID
return self.authID
def sshexeccmdrefile(self,ips,key):
try:
paramiko.util.log_to_file("paramiko.log")
print "log"
idrsa="D:\\PATH\\id_rsa" #idrsa的路径
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
pkey = paramiko.RSAKey.from_private_key_file(idrsa)
ssh.connect(hostname=ips, port=22, username='root',pkey=pkey,timeout=30)
t = ssh.get_transport()
sftp = paramiko.SFTPClient.from_transport(t)
cmds="/zabbixinstallpath/bin/zabbix_get -s zabbix服务器的IP地址 -p 10051 -k '{\"request\":\"queue.get\",\"sid\":\""+key+"\",\"type\": \"details\",\"limit\":800000}' > /tmp/zbqueues.txt" + "\n"
#ssh.exec_command(cmds)
#print cmds
#exit()
shs=ssh.invoke_shell()
shs.send(cmds.encode('utf8'))
time.sleep(6)#等待命令执行完成
#print shs.recv(1024).decode('UTF-8')
sftp.get("/tmp/zbqueues.txt","zbqueues.txt")
ssh.close()
return 1
except:
print "error"+ips
return 0
def reshowtime(self, cptimes):
t1 = time.localtime(cptimes)
showtimes = time.strftime("%Y-%m-%d %H:%M:%S", t1)
return showtimes
def checkdbitems(self):
itemidlists=[]
with open("zbqueues.txt", "r") as f:
content = json.load(f)
#f.close()
for fs in content["data"]:
itemidlists.append(fs["itemid"])
sqlstrs = "select items.itemid,items.name,items.key_,hosts.hostid,hosts.name as enablename,hosts.host,hosts.proxy_hostid as proxyids,interface.ip," \
"(select hosts.description from hosts where hostid = proxyids) as proxydesc," \
"(select hosts.host from hosts where hostid = proxyids) as proxyhosts " \
"from items,hosts,interface where items.hostid=hosts.hostid and hosts.hostid=interface.hostid and items.itemid in {}" .format(tuple(itemidlists)) + "order by proxyids"
import pysql
q1=pysql.conn_mysql()
q1.db_host="ZABBIX数据库服务器的IP"
q1.db_user="数据库用户名,不改动数据库,只读权限即可"
q1.db_passwd="数据库密码"
q1.database="ZABBIX数据库名称"
datas=q1.query_mysqlrelistss(sqlstrs)
redatas=[]
for rows in datas:
for fs in content["data"]:
if fs["itemid"]==rows["itemid"]:
now = time.time()
lasts = int(now) - int(fs["nextcheck"])
if lasts > 800: #大于800秒的写入LIST
rows["nextcheck"]=self.reshowtime(fs["nextcheck"])
#print rows["ip"],rows["enablename"],rows["name"],rows["proxyhosts"],rows["nextcheck"]
redatas.append(rows)
break
return redatas
二.查询后台ZABBIX数据库的实现
import pysql这里调用了一个查询ZABBIX后台数据库的类,实现如下:
pysql.py
#coding:utf-8
import pymysql
class conn_mysql:
def __init__(self):
self.db_host = 'DBIP'
self.db_user = 'DBUSERNAME'
self.db_passwd = 'PASSOWRD'
self.database = "DBNAME"
def query_mysqlrelists(self, sql):
conn = pymysql.connect(host=self.db_host, user=self.db_user, passwd=self.db_passwd,database=self.database)
cur = conn.cursor()
cur.execute(sql)
data = cur.fetchall()
cur.close()
conn.close()
if data != None and len(data) > 0:
return data
#调用方式:for ids, in datas:
else:
return "error"
#pymysql连接可引用列名query_mysqlrelistss:conn = pymysql.connect(host=self.db_host, user=self.db_user, passwd=self.db_passwd,database=self.database,cursorclass=pymysql.cursors.DictCursor) 解决:tuple indices must be integers, not str
def query_mysqlrelistss(self, sql):
conn = pymysql.connect(host=self.db_host, user=self.db_user, passwd=self.db_passwd,database=self.database,cursorclass=pymysql.cursors.DictCursor)
cur = conn.cursor()
cur.execute(sql)
data = cur.fetchall()
cur.close()
conn.close()
if data != None and len(data) > 0:
return data
else:
return "error"
三.django相关的实现
django项目views.py处理请求的方法
@login_required
def get_zbqueues(request):
try:
lists=imports.getqueuelists()
except Exception:
return render(request, "zbxqueues.html", {"login_err": "getimportsfail"})
paginator = Paginator(lists, 60000) # 每页的行数
page = request.GET.get('page')
try:
uplistspage = paginator.page(page)
except PageNotAnInteger:
uplistspage = paginator.page(1)
except EmptyPage:
uplistspage = paginator.page(paginator.num_pages)
return render(request,'zbxqueues.html',{'uplists':uplistspage})
urls.py加一行:
url(r'^get_zbqueues/', views.get_zbqueues,name='get_zbqueues'),
views.py调用了imports.getqueuelists()方法,这个方法调用了前面的chkzbqueue类来获取LIST返回给views.py里面的方法文章来源:https://www.toymoban.com/news/detail-490256.html
def getqueuelists():
import chkzbqueue
qs=chkzbqueue.chkzbqueues()
keys=qs.user_login()
qs.sshexeccmdrefile("执行zabbix_get客户机的IP",keys) #paramiko ssh远程连接,必须有认证密钥
lists=qs.checkdbitems()
return lists
写一个粗糙的HTML页面:文章来源地址https://www.toymoban.com/news/detail-490256.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ZABBIX800秒以上的队列</title>
</head>
<body>
{% for row in uplists %}
<td>IP地址:{{ row.ip }}</td></br>
<td>可见名称:{{ row.enablename }}</td></br>
<td>代理主机:{{ row.proxyhosts }}</td></br>
<td>监控项名称:{{ row.name}}</td></br>
<td>key:{{ row.key_ }}</td></br>
<td>上次检查的时间:{{ row.nextcheck }}</td></br>
</br> </td>
<hr style="height:3px;border:none;border-top:3px double red;" />
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if uplists.has_previous %}
<a href="?page={{ uplists.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ uplists.number }} of {{ uplists.paginator.num_pages }}.
</span>
{% if uplists.has_next %}
<a href="?page={{ uplists.next_page_number }}">next</a>
{% endif %}
</span>
</div>
</body>
</html>
到了这里,关于DJANGO查询ZABBIX6长时间的监控队列的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!