python 版本:python3
zabbix-api.py
目錄結(jié)構(gòu):
目錄結(jié)構(gòu).png
get_zabbix.py
# - * - coding: utf-8 - * -
"""Zabbix-Api Get-Data CLI.
Usage:[]
get_zabbix.py download_graph --host=<kn> --graphname=<kn>
get_zabbix.py get_max_network --host=<kn> --monitor_name=<kn>
get_zabbix.py -h | --help
get_zabbix.py --version
Options:
download_graph download specific picture from zabbix.
get_max_network get the max traffic of network.
--host=<kn> input remote host ip.
-h, --help display this help and exit.
--version output version information and exit.
Example:
get_zabbix.py download_graph --host="xxx" --graphname="網(wǎng)卡流量 eth0"
get_zabbix.py get_max_network --host="xxx" --monitor_name="net.if.out[eth0]"
"""
from docopt import docopt
from action import module
def action_route(doc_args):
if doc_args.get("download_graph"):
module.get_graph(doc_args.get("--host"), doc_args.get("--graphname"))
elif doc_args.get("get_max_network"):
module.Get_max_network(doc_args.get("--host"), doc_args.get("--monitor_name"))
else:
print("An unreasonable parameters")
if __name__ == '__main__':
args = docopt(__doc__, version='Zabbix-Api-Get CLI 1.0')
action_route(args)
2.module.py
# - * - coding: utf-8-sig - * -
import json
import requests
import urllib
import datetime,time
import http.cookiejar
import xlsxwriter
import os
from conf import get_value
urls = 'http://xxx/zabbix/api_jsonrpc.php'
user = get_value.get_message("user")
password = get_value.get_message("password")
gr_url = "http://xxx/zabbix/chart2.php"
login_url = 'http://xxx/zabbix/index.php'
endtime = time.time()
starttime = int(time.mktime((datetime.datetime.now() - datetime.timedelta(days = 7)).timetuple()))
dirs = r"E:\work\xxx\%s" %(datetime.datetime.now().strftime('%Y%m%d'))
parms = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": user,
"password": password
},
"id": 1
}
headers = {
'Content-Type': 'application/json'
}
login_data = urllib.parse.urlencode({
"name": user,
"password": password,
"autologin": 1,
"enter": "Sign in"}).encode(encoding='UTF8')
# 獲取token
def get_token():
req = requests.get(urls, headers=headers, data=json.dumps(parms))
key = req.text
dic = json.loads(key)
token = dic['result']
return token
# 獲取主機的id
def get_hostid(hostnameid):
hostid_parms = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter": {
"host": [
hostnameid
]
}
},
"auth": get_token(),
"id": 1
}
hostid = requests.get(urls, headers=headers, data=json.dumps(hostid_parms))
result = json.loads(hostid.text)['result'][0]['hostid']
return result
def getgraphid(hostname,graphname):
'''定義通過hostid獲取graphid的函數(shù)'''
values = {
"jsonrpc": "2.0",
"method": "graph.get",
"params": {
"output": "name",
"hostids": get_hostid(hostname),
"sortfield": "name",
"filter": {
"name": graphname
}
},
"auth": get_token(),
"id": 10
}
req = requests.get(urls, headers=headers, data=json.dumps(values)).text
result = json.loads(req)['result'][0]['graphid']
return result
def get_graph(hostname,graphname):
'''download graph from zabbix api'''
graph_args = urllib.parse.urlencode({
"graphid": getgraphid(hostname,graphname),
"width":'1200',
"height":'156',
"stime":starttime, #圖形開始時間
"period":'604800'}).encode(encoding='UTF8')
cj = http.cookiejar.CookieJar() # 設(shè)置一個cookie處理器, 它負(fù)責(zé)從服務(wù)器下載cookie到本地采够,并且在發(fā)送請求時帶上本地的cookie
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
urllib.request.install_opener(opener)
opener.open(login_url, login_data).read()
data = opener.open(gr_url, graph_args).read()
if os.path.exists(dirs):
pass
else:
os.makedirs(dirs)
with open(r"%s\%s.png" % (dirs, hostname), 'wb') as f:
f.write(data)
def items_get(hostname, monitor_name):
items_get_network = {
"jsonrpc": "2.0",
"method": "item.get",
"params":{
"output":"itemids",
"hostids": get_hostid(hostname),
"search":{
'key_': monitor_name
},
},
"auth":get_token(),
"id":0
}
req = requests.get(urls, headers=headers, data=json.dumps(items_get_network)).text
result = json.loads(req)['result'][0]['itemid']
return result
def Get_max_network(hostname, monitor_name):
'''獲取一周內(nèi)最大的監(jiān)控值'''
test = {
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"output": "extend",
"history": 3,
"itemids": items_get(hostname, monitor_name),
"sortfield": "clock",
"sortorder": "DESC",
"time_from": starttime,
"time_till": endtime
},
"auth": get_token(),
"id": 0
}
req = requests.get(urls, headers=headers, data=json.dumps(test)).text
result = json.loads(req)['result']
li = []
for i in result:
li.append(int(i['value']))
li.sort()
return str(round(li[-1]/1000/1000,2))+" Mbps"
# get_token()
3.get_value.py
# - * - coding: utf-8-sig - * -
import configparser
def get_message(value):
cf = configparser.ConfigParser()
cf.read(r'E:\work\zabbix-graph\get-zabbix\conf\config.ini',encoding="utf-8-sig")
return cf.get("info",value)
4.config.ini
[info]
user=xxx
password=xxx