#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17/8/28 上午9:09
# @Author : lee
# @File : ZabbixMaps.py
# @Software: PyCharm
# 说明: 输入机器要查询的园区 知道序号后,第二次 园区+序号出图 阿里 m6 园区命令分别是(ali,m6,yq)
import urllib.request
import http.cookiejar
import http
import urllib.parse
import urllib.request
import json
import requests
from prettytable import PrettyTable
import time
import sys
t = str(time.time()).replace('.', '') #去掉.的时间戳 用于给图片命名
dict_maps_name = {}
class ZabbixMaps:
def __init__(self,area,number=-1):#,number):#),graph):
self.area = area
self.number = int(number)
#self.number = number
# self.graph = graph #
self.header = {"Content-Type": "application/json-rpc"}
def get_Area_url(self): # 获得token 并返回
if self.area == 'area1':
url_head = 'xxx.xxxx/' # 写的网址的头,一会要接其他网址
elif self.area == 'm6':
url_head = 'xxxxxx/'
elif self.area == 'yq':
url_head = '172.18.2.99'
self.url_little = url_head
url = 'http://%s/zabbix/api_jsonrpc.php'% url_head
return url
def get_token(self): # 获得token 并返回
data = {"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": ' ',
"password": ' ',
},
"id": 1,
"auth": None
}
token = requests.post(url=self.get_Area_url(), headers=self.header, data=json.dumps(data))
json_dict_token = json.loads(token.text)
# print(json_dict_token['result'])
#print(json_dict_token['result'])
return json_dict_token['result']
def get_mapid(self):
counter = 0
data = {
"jsonrpc": "2.0",
"method": "map.get",
"params": {
"output":["name","sysmapoid"], # ["hostid","name"],
},
"auth": self.get_token(),
"id": 1
}
# #url_m6 = 'http://xxx/zabbix/api_jsonrpc.php'
hosts = requests.post(url=self.get_Area_url(), headers=self.header, data=json.dumps(data))
json_dict_mapid = json.loads(hosts.text)
#json_dict_hostid_result = json_dict_hostid['result'][0]['hostid']
#print(json_dict_mapid['result'])
tables = PrettyTable(['序号','监控项'])
tables.align['序号','监控项'] = 'c'
tables.horizontal_char = '-'
tables.junction_char = "-"
tables.left_padding_width = 3
for i in json_dict_mapid['result']:
dict_maps_name[counter]=i['sysmapid'],i['name']
counter += 1
# return json_dict_mapid['result']
for i in dict_maps_name:
tables.add_row([i,dict_maps_name[i][1]])
if self.number == -1:
print(tables)
print('请输入机房位置和序号:')
else:
#print(dict_maps_name)
return dict_maps_name
def url_jpg(self):
if self.number == -1:
url_jpg = -1
else:
# print(dict_graphid_name[1])
mapid = self.get_mapid()[self.number][0]
#print(self.get_mapid()[self.number][0])
url_jpg = 'http://%s/zabbix/map.php?noedit=1&sysmapid=%s' % (self.url_little,mapid)
#url_2hours = 'http://%s/zabbix/xxx.php?graphid=%s&period=7200' % (self.get_IP_Area(),self.graph_id)
#print(url_jpg)
return url_jpg
def get_jpg(self):
#print(type(self.get_IP_Area()))
# post数据接收和处理的页面
posturl = 'http://%s/zabbix/index.php?request=charts.php' % self.url_little # 从数据包中分析出,处理post请求的url
#print(posturl)
#Referer: http://xxx.ops.com.cn/zabbix/index.php?request=charts.php%3Fddreset%3D1
# 设置一个cookie处理器,它负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
cj = http.cookiejar.LWPCookieJar()
cookie_support = urllib.request.HTTPCookieProcessor(cj)
opener = urllib.request.build_opener(cookie_support, urllib.request.HTTPHandler)
urllib.request.install_opener(opener)
# 构造header,一般header至少要包含一下两项。这两项是从抓到的包里分析得出的。
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0',
'Referer': 'http://xxx.ops.xxx.com.cn/zabbix/index.php'}
# 构造Post数据,他也是从抓大的包里分析得出的。
postData = { 'name': ' ',
'password': ' ',
'autologin':1,
'enter':'Sign in'
}
# 需要给Post数据编码
postData = urllib.parse.urlencode(postData).encode('utf-8')
# 通过urllib2提供的request方法来向指定Url发送我们构造的数据,并完成登录过程
request = urllib.request.Request(posturl, postData, headers)
response = urllib.request.urlopen(request)
text = response.read().decode()
#下载图片
jpg_link = self.url_jpg() #图片链接
if jpg_link == -1:
pass
else:
path = '/Users/lee/PycharmProjects/pythonProjects//zabbix/ZabbixMaps/ZAbbixMap.jpg' #%s_%s.jpg' % (self.graph_id,t)
urllib.request.urlretrieve(jpg_link, path)
if __name__ == "__main__":
#一个参数
# item = ZabbixMaps('ali')
# item.url_jpg()
# item.get_mapid()
# 两个参数
item = ZabbixMaps('ali',2)
# item.get_token()
# item.get_mapid()
# item.url_jpg()
# item.get_jpg()
# print('图片下载完成!')
if len(sys.argv) == 2:
try:
item = ZabbixMaps(sys.argv[1])
item.url_jpg()
item.get_mapid()
except:
print("输入有误")
elif len(sys.argv) != 2:
try:
item = ZabbixMaps(sys.argv[1],sys.argv[2])
# item.get_token()
#item.get_mapid()
item.url_jpg()
item.get_jpg()
print('图片下载完成!')
except:
print("选项输入有误")
网友评论