-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathzgetgraph.py
executable file
·217 lines (178 loc) · 6.42 KB
/
zgetgraph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/env python
#
# import needed modules.
# pyzabbix is needed, see https://github.com/lukecyca/pyzabbix
#
# Pillow is also needed, see https://github.com/python-pillow/Pillow
#
#
import argparse
import ConfigParser
import os
import os.path
import distutils.util
import requests
import time
import sys
from cStringIO import StringIO
from PIL import Image
from pyzabbix import ZabbixAPI
# define config helper function
def ConfigSectionMap(section):
dict1 = {}
options = Config.options(section)
for option in options:
try:
dict1[option] = Config.get(section, option)
if dict1[option] == -1:
DebugPrint("skip: %s" % option)
except:
print("exception on %s!" % option)
dict1[option] = None
return dict1
# set default vars
try:
defconf = os.getenv("HOME") + "/.zbx.conf"
except:
defconf = None
username = ""
password = ""
api = ""
noverify = ""
# Define commandline arguments
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description='Downloads a graph from Zabbix frontend', epilog="""
This program can use .ini style configuration files to retrieve the needed API connection information.
To use this type of storage, create a conf file (the default is $HOME/.zbx.conf) that contains at least the [Zabbix API] section and any of the other parameters:
[Zabbix API]
username=johndoe
password=verysecretpassword
api=https://zabbix.mycompany.com/path/to/zabbix/frontend/
no_verify=true
""")
parser.add_argument('graphid', help='The graph that we are going to download')
parser.add_argument('-f', '--filename', required=True, help='filename to save the graph to, use - to use stdout')
parser.add_argument('-u', '--username', help='User for the Zabbix api and frontend')
parser.add_argument('-p', '--password', help='Password for the Zabbix user')
parser.add_argument('-a', '--api', help='Zabbix URL')
parser.add_argument('--no-verify', help='Disables certificate validation when using a secure connection',action='store_true')
parser.add_argument('-c','--config', help='Config file location (defaults to $HOME/.zbx.conf)')
parser.add_argument('-t', '--timeperiod', type=int, default=3600, help='Timeperiod for the graph in seconds (defaults to 3600)')
parser.add_argument('-s', '--starttime', type=int, help='Starting time for the graph in seconds from Unix Epoch')
parser.add_argument('-W', '--width', type=int, help='Width of the graph (defaults to the graph default)')
parser.add_argument('-H', '--height', type=int, help='Height of the graph (defaults to the graph default)')
args = parser.parse_args()
# load config module
Config = ConfigParser.ConfigParser()
Config
# if configuration argument is set, test the config file
if args.config:
if os.path.isfile(args.config) and os.access(args.config, os.R_OK):
Config.read(args.config)
# if not set, try default config file
else:
if os.path.isfile(defconf) and os.access(defconf, os.R_OK):
Config.read(defconf)
# try to load available settings from config file
try:
username=ConfigSectionMap("Zabbix API")['username']
password=ConfigSectionMap("Zabbix API")['password']
api=ConfigSectionMap("Zabbix API")['api']
noverify=bool(distutils.util.strtobool(ConfigSectionMap("Zabbix API")["no_verify"]))
except:
pass
# override settings if they are provided as arguments
if args.username:
username = args.username
if args.password:
password = args.password
if args.api:
api = args.api
if args.no_verify:
noverify = args.no_verify
# test for needed params
if not username:
sys.exit("Error: API User not set")
if not password:
sys.exit("Error: API Password not set")
if not api:
sys.exit("Error: API URL is not set")
# Setup Zabbix API connection
zapi = ZabbixAPI(api)
if noverify is True:
zapi.session.verify = False
# Login to the Zabbix API
zapi.login(username, password)
##################################
# Start actual API logic
##################################
# set the hostname we are looking for
graphid = args.graphid
# Find graph from API
graph = zapi.graph.get(output="extend", graphids=graphid)
if graph:
#print(format(graph))
# Set width and height
if args.width:
width = args.width
else:
width = graph[0]['width']
if args.height:
height = args.height
else:
height = graph[0]['height']
# Select the right graph generator according to graph type
# type 3 = Exploded graph
if graph[0]['graphtype'] == "3":
generator = "chart6.php"
# type 2 = Pie graph
elif graph[0]['graphtype'] == "2":
generator = "chart6.php"
# type 1 = Stacked graph
elif graph[0]['graphtype'] == "1":
generator = "chart2.php"
# type 0 = Normal graph
elif graph[0]['graphtype'] == "0":
generator = "chart2.php"
# catch-all in case someone invents a new type/generator
else:
generator = "chart2.php"
# Set time period
period = args.timeperiod
# set the starting time for the graph
if args.starttime:
stime=args.starttime
else:
stime=time.time()-period
# Set login URL for the Frontend (frontend access is needed, as we cannot retrieve graph images via the API)
loginurl = api + "/index.php"
# Data that needs to be posted to the Frontend to log in
logindata = {'autologin' : '1', 'name' : username, 'password' : password, 'enter' : 'Sign in'}
# We need to fool the frontend into thinking we are a real browser
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0', 'Content-type' : 'application/x-www-form-urlencoded'}
# setup a session object so we can reuse session cookies
session=requests.session()
if noverify == True:
verify=False
else:
verify=True
# Login to the frontend
login=session.post(loginurl, params=logindata, headers=headers, verify=verify)
# See if we logged in successfully
try:
if session.cookies['zbx_sessionid']:
# Build the request for the graph
graphurl = api + "/" + generator + "?graphid=" + str(graphid) + "&period=" + str(period) + "&width=" + str(width) + "&height=" + str(height) + "&stime=" + str(stime)
# get the graph
graphreq = session.get(graphurl,verify=verify)
# read the data as an image
graphpng = Image.open(StringIO(graphreq.content))
# and write it to file
if args.filename == "-":
graphpng.save(sys.stdout, "PNG")
else:
graphpng.save(args.filename)
except:
sys.exit("Error: Could not log in to retrieve graph")
else:
sys.exit("Error: Could not find graphid "+ graphid)
# And we're done...