微信網(wǎng)站開發(fā)合同成都推廣團(tuán)隊(duì)
有時(shí)候被ZABBIX監(jiān)控的主機(jī)可能需要關(guān)機(jī)重啟等維護(hù)操作,為了在此期間不觸發(fā)告警,需要?jiǎng)?chuàng)建主機(jī)的維護(hù)任務(wù),以免出現(xiàn)誤告警
ZABBIX本身有這個(gè)API可供調(diào)用(不同版本細(xì)節(jié)略有不同,本次用的ZABBIX6.*),實(shí)現(xiàn)批量化建立主機(jī)的維護(hù)任務(wù)
無論哪種方式(IP列表,主機(jī)描述,或IP子網(wǎng))創(chuàng)建維護(hù),都是向maintenance.create這個(gè)方法傳遞參數(shù)的過程,除了起始和終止的時(shí)間,最主要的一個(gè)參數(shù)就是hostids這個(gè)參數(shù),它是一個(gè)列表(也可以是單個(gè)hostid)
def create_host_maintenance(self,names,ips,starttimes,stoptimes):starts=self.retimes(starttimes)stops=self.retimes(stoptimes)data = json.dumps({"jsonrpc":"2.0","method":"maintenance.create","params": {"name": names,"active_since": starts,"active_till": stops,#"hostids": [ "12345","54321" ],"hostids": ips,"timeperiods": [{"timeperiod_type": 0,"start_date": starts,#"start_time": 0,zabbix6不用這個(gè)參數(shù),低版本的有用"period": int(int(stops)-int(starts))}]},"auth": self.authID,"id": 1,})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 "Error as ", eelse:response = json.loads(result.read())result.close()print "maintenance is created!"
1.簡(jiǎn)單說明hostids這個(gè)列表參數(shù)產(chǎn)生的過程
按IP列表產(chǎn)生hostids的LIST,并調(diào)用方法創(chuàng)建維護(hù)
def djmaintenanceiplist(self,ipliststr="strs",area="none",byip="none"):lists = []if area=="none": #通過IP列表來創(chuàng)建維護(hù),只向函數(shù)傳遞ipliststr這個(gè)參數(shù),其它參數(shù)為空for line in ipliststr.splitlines():con = line.split()ipaddr = con[0].strip()hostids = self.host_getbyip(ipaddr)if hostids != "error" and hostids not in lists:lists.append(hostids)return listselse:if area !="ip" and ipliststr != "strs": #按主機(jī)描述匹配創(chuàng)建維護(hù),ipliststr參數(shù)因定為strs,area參數(shù)為主機(jī)描述,byip參數(shù)為空(因?yàn)榫W(wǎng)絡(luò)環(huán)境的原因,本例棄用這個(gè)條件)sqls="select hostid from zabbixdb.hosts where name like '%"+area+"%' "tests=pysql.conn_mysql()datas=tests.query_mysqlrelists(sqls)if datas != "error":for ids, in datas:if ids not in lists:lists.append(ids)else:if byip != "none": #按主機(jī)IP子網(wǎng)創(chuàng)建維護(hù),byip參數(shù)不為空(因?yàn)榫W(wǎng)絡(luò)環(huán)境的原因,本例棄用這個(gè)條件)sqls = "select hosts.hostid from zabbixdb.hosts,zabbixdb.interface where `hosts`.hostid=interface.hostid and (interface.ip like '%" + byip + "%' or hosts.name like '%" + byip + "%')"tests = pysql.conn_mysql()datas = tests.query_mysqlrelists(sqls)if datas != "error":for ids, in datas:if ids not in lists:lists.append(ids)return listsdef djiplist(self,starttime,stoptime,strlins): #strlins為IP列表的參數(shù),可由WEB前端傳遞進(jìn)來test = ZabbixTools()test.user_login()lists = test.djmaintenanceiplist(strlins)nowtime = str(time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())))test.create_host_maintenance(nowtime, lists, starttime, stoptime)
按主機(jī)描述和IP子網(wǎng)產(chǎn)生hostids的LIST,并調(diào)用方法創(chuàng)建維護(hù)
def djdescript(self,starttime,stoptime,descstr,ipnets="none"):lists = []if descstr != "ip": #descstr參數(shù)不為ip的時(shí)候,表示根據(jù)主機(jī)的描述信息匹配創(chuàng)建維護(hù),此時(shí)不傳遞innets參數(shù)for line in descstr.splitlines():con = line.split()descstrnew = con[0].strip()sqls = "select hostid from dbname.hosts where name like '%" + descstrnew + "%' "tests = pysql.conn_mysql()datas = tests.query_mysqlrelists(sqls)if datas != "error":for ids, in datas:if ids not in lists:lists.append(ids)else:if ipnets != "none": #ipnets參數(shù)不為空,表示按照IP子網(wǎng)匹配創(chuàng)建維護(hù),此時(shí)descstr參數(shù)一定為"ip"sqls = "select hosts.hostid from dbname.hosts,dbname.interface where `hosts`.hostid=interface.hostid and (interface.ip like '%" + ipnets + "%' or hosts.name like '%" + ipnets + "%')"tests = pysql.conn_mysql()datas = tests.query_mysqlrelists(sqls)if datas != "error":for ids, in datas:if ids not in lists:lists.append(ids)test = ZabbixTools()test.user_login()nowtime = str(time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())))test.create_host_maintenance(nowtime, lists, starttime, stoptime)
2.create_host_maintenance和djmaintenanceiplist,及djdescript函數(shù)調(diào)用方法的說明
時(shí)間轉(zhuǎn)換函數(shù)self.retimes,將用戶傳遞/的"%Y-%m-%d %H:%M:%S"日期時(shí)間轉(zhuǎn)換為時(shí)間時(shí)間戳
def retimes(self,times):timeArray = time.strptime(times, "%Y-%m-%d %H:%M:%S")timestamp = time.mktime(timeArray)return timestamp
self.host_getbyip(ipaddr)通過主機(jī)IP獲取zabbix的hostid,這個(gè)方法應(yīng)用很廣泛
函數(shù)中的self.authID通過zabbix的API 的"user.login"方法獲取,參考ZABBIX官方文檔
def host_getbyip(self,hostip):data = json.dumps({"jsonrpc":"2.0","method":"host.get","params":{"output":["hostid","name","status","available"],"filter": {"ip": hostip,"custom_interfaces":0}},"auth":self.authID,"id":1,})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:if hasattr(e, 'reason'):print 'We failed to reach a server.'print 'Reason: ', e.reasonelif hasattr(e, 'code'):print 'The server could not fulfill the request.'print 'Error code: ', e.codeelse:response = json.loads(result.read())result.close()lens=len(response['result'])if lens > 0:return response['result'][0]['hostid']else:print "error "+hostipreturn "error"
pysql.conn_mysql()的實(shí)現(xiàn)
#coding:utf-8
import pymysql
class conn_mysql:def __init__(self):self.db_host = 'zabbixdbip'self.db_user = 'dbusername'self.db_passwd = 'dbuserpassword'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()#print data# 查詢到有數(shù)據(jù)則進(jìn)入行判斷,row有值且值有效則取指定行數(shù)據(jù),無值則默認(rèn)第一行if data != None and len(data) > 0:return data#調(diào)用方式:for ids, in datas:else:return "error"#此方法返回的數(shù)據(jù)不含數(shù)據(jù)庫(kù)字段的列表,如果要返回包含列名(KEY)的字典列表,則: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
3.VIEWS.PY及前端和前端偉遞參數(shù)的說明
views.py對(duì)應(yīng)的方法
#@login_required
def zabbixmanage(request):if request.method=="POST":uptime = request.POST.get('uptime')downtime= request.POST.get('downtime')UTC_FORMAT = "%Y-%m-%dT%H:%M"utcTime = datetime.datetime.strptime(uptime, UTC_FORMAT)uptime = str(utcTime + datetime.timedelta(hours=0))utcTime = datetime.datetime.strptime(downtime, UTC_FORMAT)downtime = str(utcTime + datetime.timedelta(hours=0))if request.POST.has_key('iplists'):try:sqlstr=request.POST.get("sqlstr")u1=upproxy.ZabbixTools() #前面的python文件名為upproxy.py,類名為ZabbixToolsu1.djiplist(uptime,downtime,sqlstr)except Exception:return render(request,"zbx1.html",{"login_err":"FAILSTEP1"})if request.POST.has_key('descs'):try:sqlstr = request.POST.get("sqlstr")u1 = upproxy.ZabbixTools() u1.djdescript(uptime,downtime,sqlstr)except Exception:return render(request,"zbx1.html",{"login_err":"FAILSTEP2"})if request.POST.has_key('ipnets'):try:sqlstr = request.POST.get("sqlstr")u1 = upproxy.ZabbixTools()u1.djdescript(uptime,downtime,"ip",sqlstr)except Exception:return render(request,"zbx1.html",{"login_err":"FAILSTEP3"})
HTML的簡(jiǎn)單寫法,不太會(huì)寫,很潦草
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>ZABBIXMANAGE</title>
</head>
<body><div id="container" class="cls-container"><div id="bg-overlay" ></div><div class="cls-header cls-header-lg"><div class="cls-brand"><h3>ZABBIX主機(jī)維護(hù)模式</h3><h4>開始時(shí)間小于結(jié)束時(shí)間</h4></div></div><div class="cls-content"><div class="cls-content-sm panel"><div class="panel-body"><form id="loginForm" action="{% url 'zabbixmanage' %}" method="POST"> {% csrf_token %}<div class="form-group"><div class="input-group"><div class="input-group-addon"><i class="fa fa-user"></i></div><textarea type="text" class="form-control" name="sqlstr" placeholder="IP列表,關(guān)鍵字或者IP網(wǎng)段" style="width:300px;height:111px"></textarea></br></div></div></br></br>開始時(shí)間:<input type="datetime-local" name="uptime"></br></br>結(jié)束時(shí)間:<input type="datetime-local" name="downtime"></br></br><p class="pad-btm">按IP列表維護(hù):按行輸入IP列表加入維護(hù),一行一個(gè)IP,多行輸入</p><p class="pad-btm">按關(guān)鍵字匹配:主機(jī)描述信息的關(guān)鍵字匹配的加入維護(hù),一般用于虛擬機(jī)宿主機(jī)和關(guān)鍵字匹配</p><p class="pad-btm">匹配子網(wǎng)關(guān)鍵字維護(hù):IP網(wǎng)段匹配的加入維護(hù),一次填寫一個(gè)子網(wǎng),多個(gè)子網(wǎng)多次設(shè)置,寫法示例:172.16.</p><button class="btn btn-success btn-block" type="submit" name="iplists"><b>按IP列表維護(hù)一般情況用這個(gè)就行</b></button></br></br><button class="btn btn-success btn-block" type="submit" name="descs"><b>按關(guān)鍵字匹配</b></button><button class="btn btn-success btn-block" type="submit" name="ipnets"><b>匹配子網(wǎng)關(guān)鍵字維護(hù)</b></button><h4 style="color: red"><b>{{ login_err }}</b></h4></form></div></div></div> </div>
</body>
</html>
跑起來大約是這個(gè)界面,用戶填寫主機(jī)IP列表,或匹配的描述,或子網(wǎng)的信息,選好時(shí)間,點(diǎn)個(gè)按鈕就能實(shí)現(xiàn)批量的維護(hù)任務(wù)