-
Notifications
You must be signed in to change notification settings - Fork 8
/
prtg.py
695 lines (678 loc) · 32.5 KB
/
prtg.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
import os
import csv
import requests
import warnings
from datetime import datetime,timedelta
from bs4 import BeautifulSoup,XMLParsedAsHTMLWarning
from requests.packages.urllib3.exceptions import InsecureRequestWarning
warnings.filterwarnings('ignore', category=XMLParsedAsHTMLWarning)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
#class used by prtg_api and children to manage global arrays of all objects
class global_arrays(object):
allprobes = []
allgroups = []
alldevices = []
allsensors = []
#class used by all prtg_* objects to build urls and query prtg using requests
class connection_methods(object):
def unpack_config(self,confdata):
self.host = confdata[0]
self.port = confdata[1]
self.user = confdata[2]
self.passhash = confdata[3]
self.protocol = confdata[4]
self.apikey = confdata[5]
self.confdata = confdata
self.base_url = "{protocol}://{host}:{port}/api/".format(protocol=self.protocol,host=self.host,port=self.port)
self.base_url_no_api = "{protocol}://{host}:{port}/".format(protocol=self.protocol,host=self.host,port=self.port)
if self.user is None and self.passhash is None and self.apikey is None:
raise(self.AuthenticationError("Please supply username & passhash or api key"))
elif self.apikey is None:
if self.user is None or self.passhash is None:
raise(self.AuthenticationError("Please supply both username & passhash"))
if self.apikey is not None:
self.url_auth = "apitoken={apitoken}".format(apitoken=self.apikey)
else:
self.url_auth = "username={username}&passhash={passhash}".format(username=self.user,passhash=self.passhash)
def get_request(self,url_string,api=True):
#global method for api calls. Provides errors for the 401 and 404 responses
if api:
url = "{base}{content}&{auth}".format(base=self.base_url,content=url_string,auth=self.url_auth)
else:
url = "{base}{content}&{auth}".format(base=self.base_url_no_api,content=url_string,auth=self.url_auth)
req = requests.get(url,verify=False)
if req.status_code == 200 or req.status_code == 302:
return(req)
elif req.status_code == 401:
raise(self.AuthenticationError("PRTG authentication failed. Check credentials in config file"))
elif req.status_code == 404:
raise(self.ResourceNotFound("No resource at URL used: {0}".format(tree_url)))
class baseconfig(connection_methods):
def __str__(self):
return("<Name: {name}, ID: {id}, Active: {active}>".format(name=self.name,id=self.id,active=self.active))
def __repr__(self):
return("<Name: {name}, ID: {id}, Active: {active}>".format(name=self.name,id=self.id,active=self.active))
def clear_arrays(self):
del self.allprobes[:]
del self.allgroups[:]
del self.alldevices[:]
del self.allsensors[:]
def delete(self,confirm=True):
if self.type == "Root":
return("You cannot delete the root object.")
else:
delete_url = "deleteobject.htm?id={objid}&approve=1".format(objid=self.id)
if confirm:
response = ""
while response.upper() not in ["Y","N"]:
response = str(input("Would you like to continue?(Y/[N]) "))
if response == "":
response = "N"
if response.upper() == "Y":
req = self.get_request(url_string=delete_url)
else:
req = self.get_request(url_string=delete_url)
def set_property(self,name,value):
if self.type != "Channel":
setprop_url = "setobjectproperty.htm?id={objid}&name={propname}&value={propval}".format(objid=self.id,propname=name,propval=value)
else:
setprop_url = "setobjectproperty.htm?id={objid}&subid={subid}&name={propname}&value={propval}".format(objid=self.sensorid,subid=self.objid,propname=name,propval=value)
req = self.get_request(url_string=setprop_url)
self.name = value
def get_property(self,name):
if self.type != "Channel":
getprop_url = "getobjectproperty.htm?id={objid}&name={propname}&show=text".format(objid=self.id,propname=name)
else:
getprop_url = "getobjectproperty.htm?id={objid}&subid={subid}&name={propname}".format(objid=self.sensorid,subid=self.objid,propname=name)
req = self.get_request(url_string=getprop_url)
soup = BeautifulSoup(req.text,'lxml')
if soup.result.text != "(Property not found)":
setattr(self,name,soup.result.text)
return(soup.result.text)
else:
raise(self.ResourceNotFound("No object property of name: {name}".format(name=name)))
def set_interval(self,interval):
'''note: you will still need to disable inheritance manually.
Valid intervals are (seconds): 30, 60, 300, 600, 900, 1800, 3600, 14400, 21600, 43200, 86400'''
self.set_property(name="interval",value=interval)
def get_tree(self,root=''):
#gets sensortree from prtg. If no rootid is provided returns entire tree
tree_url = "table.xml?content=sensortree&output=xml&id={rootid}".format(rootid=root)
req = self.get_request(url_string=tree_url)
raw_data = req.text
treesoup = BeautifulSoup(raw_data,"lxml")
#returns the xml as a beautifulsoup object
if len(treesoup.sensortree.nodes) > 0:
return(treesoup)
else:
raise(self.ResourceNotFound("No objects at ID: {id}".format(id=root)))
def rename(self,newname):
rename_url = "rename.htm?id={objid}&value={name}".format(objid=self.id,name=newname)
req = self.get_request(url_string=rename_url)
self.name = newname
def pause(self,duration=0,message=""):
if duration > 0:
pause_url = "pauseobjectfor.htm?id={objid}&duration={time}".format(objid=self.id,time=str(duration))
else:
pause_url = "pause.htm?id={objid}&action=0".format(objid=self.id)
if message:
pause_url += "&pausemsg={string}".format(string=message)
req = self.get_request(url_string=pause_url)
self.status = "Paused"
self.active = "false"
self.status_raw = "7"
def resume(self):
resume_url = "pause.htm?id={objid}&action=1".format(objid=self.id)
req = self.get_request(url_string=resume_url)
#these are question marks because we don't know what status is after resume
self.status = "?"
self.active = "true"
self.status_raw = "?"
def get_status(self, name="status"):
status_url= "getobjectstatus.htm?id={objid}&name={name}&show=text".format(objid=self.id, name=name)
req = self.get_request(url_string=status_url)
soup = BeautifulSoup(req.text,'lxml')
status = soup.result.text.strip()
self.status = status
return(status)
def clone(self,newname,newplaceid):
clone_url = "duplicateobject.htm?id={objid}&name={name}&targetid={newparent}".format(objid=self.id,name=newname,newparent=newplaceid)
req = self.get_request(url_string=clone_url)
new_url = req.history[-1].url
new_id = new_url.split('=')[-1]
return(new_id)
def add_tags(self,tags,clear_old=False):
if not isinstance(tags,list):
raise(Exception("Needs tags as type: list"))
if clear_old:
old_tags = []
else:
old_tags = self.get_property('tags').split(' ')
new_tags = " ".join(old_tags+tags)
self.set_property(name='tags',value=new_tags)
#define global arrays, inherited to all objects
class AuthenticationError(Exception):
pass
class ResourceNotFound(Exception):
pass
class prtg_api(global_arrays,baseconfig):
'''
Parameters:
- host: Enter the ip address or hostname where PRTG is running
- port: Enter the tcp port used to connect to prtg. (usually 80 or 443)
- user: Enter your PRTG username
- passhash: Enter your PRTG passhash. Can be found in PRTG webgui > settings > account settings
- protocol: Enter the protocol used to connect to PRTG server (http or https)
- rootid: Enter the id of the group/probe that contains all the objects you want to manage. Defaults to 0 (gets entire sensortree)
Example:
host = '192.168.1.1'
port = '443'
user = 'prtgadmin'
passhash = '0000000'
protocol = 'https'
rootid = '53'
prtg = prtg_api(host,user,passhash,rootid,protocol,port)
'''
def __init__(self,host,user=None,passhash=None,apikey=None,rootid=0,protocol='https',port='443'):
self.confdata = (host,port,user,passhash,protocol,apikey)
self.unpack_config(self.confdata)
self.clear_arrays()
self.probes = []
self.groups = []
self.devices = []
#get sensortree from root id downwards
self.treesoup = self.get_tree(root=rootid)
#Finds all the direct child nodes in sensortree and creates python objects, passes each object its xml data
for child in self.treesoup.sensortree.nodes.children:
if child.name is not None:
for childr in child.children:
if childr.name == "probenode":
probeobj = probe(childr,self.confdata)
self.allprobes.append(probeobj)
self.probes.append(probeobj)
elif childr.name == "device":
deviceobj = device(childr,self.confdata)
self.devices.append(deviceobj)
self.alldevices.append(deviceobj)
elif childr.name == "group":
groupobj = group(childr,self.confdata)
self.groups.append(groupobj)
self.allgroups.append(groupobj)
elif childr.name is not None:
if childr.string is None:
childr.string = ""
setattr(self,childr.name,childr.string)
def refresh(self):
#download fresh sensortree
self.treesoup = self.get_tree(root=self.id)
probeids = []
newprobeids = []
groupids = []
newgroupids = []
deviceids = []
newdeviceids = []
#get ids of existing probes
for aprobe in self.probes:
probeids.append(aprobe.id)
for agroup in self.groups:
groupids.append(agroup.id)
for adevice in self.devices:
deviceids.append(adevice.id)
#for all the child objects in sensortree, if it already exists refresh the object, otherwise create a new one
for child in self.treesoup.sensortree.nodes.children:
if child.name is not None:
for childr in child.children:
if childr.name == "probenode":
if childr.find("id").string in probeids:
for aprobe in self.probes:
if aprobe.id == childr.find("id").string:
aprobe.refresh(childr)
else:
probeobj = probe(childr,self.confdata)
self.probes.append(probeobj)
self.allprobes.append(probeobj)
#add all probe ids from the sensortree to this list
newprobeids.append(childr.find("id").string)
elif childr.name == "group":
if childr.find("id").string in groupids:
for agroup in self.groups:
if agroup.id == childr.find("id").string:
agroup.refresh(childr)
else:
groupobj = group(childr,self.confdata)
self.allgroups.append(groupobj)
self.groups.append(groupobj)
#add all probe ids from the sensortree to this list
newgroupids.append(childr.find("id").string)
elif childr.name == "device":
if childr.find("id").string in deviceids:
for adevice in self.devices:
if adevice.id == childr.find("id").string:
adevice.refresh(childr)
else:
deviceobj = device(childr,self.confdata)
self.alldevices.append(devicebj)
self.device.append(deviceobj)
#add all probe ids from the sensortree to this list
newdeviceids.append(childr.find("id").string)
elif childr.name is not None:
if childr.string is None:
childr.string = ""
setattr(self,childr.name,childr.string)
#if existing probes were not in the new sensortree, remove from allprobes
for id in probeids:
if id not in newprobeids:
for aprobe in self.probes:
if aprobe.id == id:
self.allprobes.remove(aprobe)
self.probes.remove(aprobe)
for id in groupids:
if id not in newgroupids:
for agroup in self.groups:
if agroup.id == id:
self.allgroups.remove(agroup)
self.groups.remove(agroup)
for id in deviceids:
if id not in newdeviceids:
for adevice in self.devices:
if adevice.id == id:
self.alldevice.remove(adevice)
self.devices.remove(adevice)
def search_byid(self,id):
id = str(id)
for obj in self.allprobes + self.allgroups + self.alldevices + self.allsensors:
if obj.id == id:
return(obj)
class channel(prtg_api):
def __init__(self,channelsoup,sensorid,confdata):
self.unpack_config(confdata)
self.sensorid = sensorid
for child in channelsoup.children:
if child.string is None:
child.string = ""
if child.name is not None:
setattr(self,child.name,child.string)
self.id = self.objid
if hasattr(self,'lastvalue'):
if self.lastvalue.replace(".","").isdigit():
try:
self.lastvalue_int = int(self.lastvalue.split(" ")[0].replace(",",""))
self.lastvalue_float = float(self.lastvalue_int)
except ValueError:
self.lastvalue_float = float(self.lastvalue.split(" ")[0].replace(",",""))
self.lastvalue_int = int(self.lastvalue_float)
self.unit = self.lastvalue.split(" ")[1]
self.type = "Channel"
def __str__(self):
return("<Name: {name}, ID: {id}>".format(name=self.name,id=self.id))
def __repr__(self):
return("<Name: {name}, ID: {id}>".format(name=self.name,id=self.id))
def rename(self,newname):
self.set_property(name="name",value=newname)
self.name = newname
def pause(self,duration=0,message=""):
print("Channels cannot be paused, pausing parent sensor.")
if duration > 0:
pause_url = "pauseobjectfor.htm?id={objid}&duration={time}".format(objid=self.sensorid,time=duration)
else:
pause_url = "pause.htm?id={objid}&action=0&".format(objid=self.sensorid)
if message:
pause_url += "&pausemsg={string}".format(string=message)
req = self.get_request(url_string=pause_url)
def resume(self):
print("Channels cannot be resumed, resuming parent sensor.")
resume_url = "pause.htm?id={objid}&action=1".format(objid=self.sensorid)
req = self.get_request(url_string=resume_url)
def refresh(self,channelsoup):
for child in channelsoup.children:
if child.string is None:
child.string = ""
if child.name is not None:
setattr(self,child.name,child.string)
self.id = self.objid
def delete(self):
return("You cannot delete a channel")
class sensor(prtg_api):
def __init__(self,sensorsoup,deviceid,confdata):
self.unpack_config(confdata)
for child in sensorsoup.children:
if child.string is None:
child.string = ""
if child.name is not None:
setattr(self,child.name,child.string)
setattr(self,"attributes",sensorsoup.attrs)
self.channels = []
self.type = "Sensor"
self.deviceid = deviceid
def get_channels(self):
channel_url = "table.xml?content=channels&output=xml&columns=name,lastvalue_,objid&id={sensorid}".format(sensorid=self.id)
req = self.get_request(url_string=channel_url)
channelsoup = BeautifulSoup(req.text,"lxml")
if len(self.channels) == 0:
for child in channelsoup.find_all("item"):
self.channels.append(channel(child,self.id,self.confdata))
else:
for child in channelsoup.find_all("item"):
for achannel in self.channels:
if achannel.objid == child.find("objid").string:
achannel.refresh(child)
def refresh(self,sensorsoup=None):
if sensorsoup is None:
soup = self.get_tree(root=self.id)
sensorsoup = soup.sensortree.nodes.sensor
for child in sensorsoup.children:
if child.string is None:
child.string = ""
if child.name is not None:
setattr(self,child.name,child.string)
setattr(self,"attributes",sensorsoup.attrs)
if len(self.channels) > 0:
self.get_channels()
def set_additional_param(self,parameterstring):
self.set_property(name="params",value=parameterstring)
def acknowledge(self,message=""):
acknowledge_url = "acknowledgealarm.htm?id={objid}&ackmsg={string}".format(objid=self.id,string=message)
req = self.get_request(url_string=acknowledge_url)
self.get_status()
def save_graph(self,graphid,filepath,size,hidden_channels='',filetype='svg'):
'''
Size options: S,M,L
'''
if size.upper() == "L":
width = "1500"
height = "500"
font = "13"
elif size.upper() == "S":
width = "400"
height = "300"
font = "9"
else:
width = "800"
height = "350"
font = "13"
if hidden_channels:
hidden_channels = "&hide={hc}".format(hc=hidden_channels)
chart_url = "chart.{ft}?type=graph&graphid={gid}&id={sid}&width={w}&height={h}{hc}&plotcolor=%23ffffff&gridcolor=%23ffffff&graphstyling=showLegend%3D%271%27+baseFontSize%3D%27{f}%27".format(
ft=filetype,gid=graphid,sid=self.id,w=width,h=height,hc=hidden_channels,f=font)
req = self.get_request(url_string=chart_url,api=False)
with open(filepath,"wb") as imgfile:
for chunk in req:
imgfile.write(chunk)
self.filepath = filepath
class device(prtg_api):
def __init__(self,devicesoup,confdata):
self.unpack_config(confdata)
self.sensors = []
for child in devicesoup.children:
if child.name == "sensor":
sensorobj = sensor(child,self.id,self.confdata)
self.sensors.append(sensorobj)
self.allsensors.append(sensorobj)
elif child.name is not None:
if child.string is None:
child.string = ""
setattr(self,child.name,child.string)
#Adds sensors to a dictionary based on their status
self.sensors_by_status = {"Up":[],"Down":[],"Warning":[],"Paused":[]}
for asensor in self.sensors:
if asensor.status in self.sensors_by_status.keys():
self.sensors_by_status[asensor.status].append(asensor)
else:
self.sensors_by_status[asensor.status] = [asensor]
setattr(self,"attributes",devicesoup.attrs)
self.type = "Device"
def refresh(self,devicesoup=None):
if devicesoup is None:
soup = self.get_tree(root=self.id)
devicesoup = soup.sensortree.nodes.device
sensorids = []
newsensorids = []
for asensor in self.sensors:
sensorids.append(asensor.id)
for child in devicesoup.children:
if child.name == "sensor":
if child.find("id").string in sensorids:
for asensor in self.sensors:
if asensor.id == child.find("id").string:
asensor.refresh(child)
else:
sensorobj = sensor(child,self.id,self.confdata)
self.sensors.append(sensorobj)
self.allsensors.append(sensorobj)
newsensorids.append(child.find("id").string)
elif child.name is not None:
if child.string is None:
child.string = ""
setattr(self,child.name,child.string)
for id in sensorids:
if id not in newsensorids:
for asensor in self.sensors:
if asensor.id == id:
sensortoremove = asensor
self.sensors.remove(sensortoremove)
self.allsensors.remove(sensortoremove)
setattr(self,"attributes",devicesoup.attrs)
def set_host(self,host):
self.set_property(name="host",value=host)
self.host = host
class group(prtg_api):
def __init__(self,groupsoup,confdata):
self.unpack_config(confdata)
self.groups = []
self.devices = []
#groupsoup is passed into __init__ method
#The children objects are either added to this object as an attribute
#or a device/group object is created
for child in groupsoup.children:
if child.name == "device":
deviceobj = device(child,self.confdata)
self.devices.append(deviceobj)
self.alldevices.append(deviceobj)
elif child.name == "group":
groupobj = group(child,self.confdata)
self.groups.append(groupobj)
self.allgroups.append(groupobj)
elif child.name is not None:
if child.string is None:
child.string = ""
setattr(self,child.name,child.string)
setattr(self,"attributes",groupsoup.attrs)
self.type = "Group"
def refresh(self,groupsoup=None):
if groupsoup is None:
if self.type == "Group":
soup = self.get_tree(root=self.id)
groupsoup = soup.sensortree.nodes.group
elif self.type == "Probe":
soup = self.get_tree(root=self.id)
groupsoup = soup.sensortree.nodes.probenode
deviceids = []
newdeviceids = []
for adevice in self.devices:
deviceids.append(adevice.id)
groupids = []
newgroupids = []
for agroup in self.groups:
groupids.append(agroup.id)
for child in groupsoup.children:
if child.name == "device":
if child.find("id").string in deviceids:
for adevice in self.devices:
if adevice.id == child.find("id").string:
adevice.refresh(child)
else:
deviceobj = device(child,self.confdata)
self.devices.append(deviceobj)
self.alldevices.append(deviceobj)
newdeviceids.append(child.find("id").string)
elif child.name == "group":
if child.find("id").string in groupids:
for agroup in self.groups:
if agroup.id == child.find("id").string:
agroup.refresh(child)
else:
groupobj = group(child,self.confdata)
self.groups.append(groupobj)
self.allgroups.append(groupobj)
newgroupids.append(child.find("id").string)
elif child.name is not None:
if child.string is None:
child.string = ""
setattr(self,child.name,child.string)
for id in deviceids:
if id not in newdeviceids:
for adevice in self.devices:
if adevice.id == id:
devicetoremove = adevice
self.devices.remove(devicetoremove)
self.alldevices.remove(devicetoremove)
for id in groupids:
if id not in newgroupids:
for agroup in self.groups:
if agroup.id == id:
grouptoremove = agroup
self.groups.remove(grouptoremove)
self.allgroups.remove(grouptoremove)
setattr(self,"attributes",groupsoup.attrs)
#probe is the same as group so it inherits all methods and attributes except type
class probe(group):
type = "Probe"
class prtg_device(baseconfig):
'''Seperate top level object to manage just a device and its sensors instead of
downloading details for an entire group'''
def __init__(self,host,user=None,passhash=None,apikey=None,deviceid=0,protocol='https',port='443'):
self.confdata = (host,port,user,passhash,protocol,apikey)
self.unpack_config(self.confdata)
self.sensors = []
soup = self.get_tree(root=deviceid)
for child in soup.sensortree.nodes.device:
if child.name == "sensor":
sensorobj = sensor(child,self.id,self.confdata)
self.sensors.append(sensorobj)
elif child.name is not None:
if child.string is None:
child.string = ""
setattr(self,child.name,child.string)
self.sensors_by_status = {"Up":[],"Down":[],"Warning":[],"Paused":[]}
for asensor in self.sensors:
if asensor.status in self.sensors_by_status.keys():
self.sensors_by_status[asensor.status].append(asensor)
else:
self.sensors_by_status[asensor.status] = [asensor]
def refresh(self):
soup = self.get_tree(root=deviceid)
sensorids = []
for asensor in self.sensors:
sensorids.append(asensor.id)
for child in soup.sensortree.nodes.device:
if child.name == "sensor":
if child.find("id").string in sensorids:
for asensor in self.sensors:
if asensor.id == child.find("id").string:
asensor.refresh(child)
else:
sensorobj = sensor(child,self.id,self.confdata)
self.sensors.append(sensorobj)
elif child.name is not None:
if child.string is None:
child.string = ""
setattr(self,child.name,child.string)
class prtg_sensor(baseconfig):
'''Seperate top level object to manage just a sensor and its channels instead of
downloading details for an entire group'''
def __init__(self,host,user=None,passhash=None,apikey=None,sensorid=0,protocol='https',port='443'):
self.confdata = (host,port,user,passhash,protocol,apikey)
self.unpack_config(self.confdata)
self.channels = []
soup = self.get_tree(root=sensorid)
for child in soup.sensortree.nodes.sensor:
if child.name is not None:
if child.string is None:
child.string = ""
setattr(self,child.name,child.string)
self.get_channels()
def refresh(self):
soup = self.get_tree(root=self.id)
for child in soup.sensortree.nodes.sensor.children:
if child.string is None:
child.string = ""
if child.name is not None:
setattr(self,child.name,child.string)
setattr(self,"attributes",sensorsoup.attrs)
self.get_channels()
def get_channels(self):
channel_url = "table.xml?content=channels&output=xml&columns=name,lastvalue_,objid&id={sensorid}".format(sensorid=self.id)
req = self.get_request(url_string=channel_url)
channelsoup = BeautifulSoup(req.text,"lxml")
if len(self.channels) == 0:
for child in channelsoup.find_all("item"):
self.channels.append(channel(child,self.id,self.confdata))
else:
for child in channelsoup.find_all("item"):
for achannel in self.channels:
if achannel.objid == child.find("objid").string:
achannel.refresh(child)
def acknowledge(self,message=""):
acknowledge_url = "acknowledgealarm.htm?id={objid}&ackmsg={string}".format(objid=self.id,string=message)
req = self.get_request(url_string=acknowledge_url)
def save_graph(self,graphid,filepath,size,hidden_channels='',filetype='svg'):
'''
Size options: S,M,L
'''
if size.upper() == "L":
width = "1500"
height = "500"
font = "13"
elif size.upper() == "S":
width = "400"
height = "300"
font = "9"
else:
width = "800"
height = "350"
font = "13"
if hidden_channels:
hidden_channels = "&hide={hc}".format(hc=hidden_channels)
chart_url = "chart.{ft}?type=graph&graphid={gid}&id={sid}&width={w}&height={h}{hc}&plotcolor=%23ffffff&gridcolor=%23ffffff&graphstyling=showLegend%3D%271%27+baseFontSize%3D%27{f}%27".format(
ft=filetype,gid=graphid,sid=self.id,w=width,h=height,hc=hidden_channels,f=font)
req = self.get_request(url_string=chart_url,api=False)
with open(filepath,"wb") as imgfile:
for chunk in req:
imgfile.write(chunk)
self.filepath = filepath
class prtg_historic_data(connection_methods):
'''class used for calls to the historic data api.
Call the class first using connection params then use
methods to get/process data. yyyy-mm-dd-hh-mm-ss'''
def __init__(self,host,user=None,passhash=None,apikey=None,port='443',protocol='https'):
self.confdata = (host,port,user,passhash,protocol,apikey)
self.unpack_config(self.confdata)
def format_date(self,dateobj):
'''Pass a datetime object and this will format appropriately
for use with the historic data api'''
return(dateobj.strftime("%Y-%m-%d-%H-%M-%S"))
def get_historic_data(self,objid,startdate,enddate,timeaverage):
if type(startdate) == datetime:
startdate = self.format_date(startdate)
if type(enddate) == datetime:
enddate = self.format_date(enddate)
historic_url = "historicdata.csv?id={id}&avg={avg}&sdate={sdate}&edate={edate}".format(id=objid,avg=timeaverage,sdate=startdate,edate=enddate)
req = self.get_request(url_string=historic_url)
csvRaw = req.text
csvLines = (csvRaw.split("\n"))[:-2]
csvReader = csv.reader(csvLines)
data = {}
for ind,row in enumerate(csvReader):
if ind == 0:
headers = row
for header in headers:
data[header] = []
else:
for inde,cell in enumerate(row):
if headers[inde] == "Date Time":
if "-" in cell:
cell = cell[:cell.index(" -")]
data[headers[inde]].append(datetime.strptime(cell,"%m/%d/%Y %I:%M:%S %p"))
else:
data[headers[inde]].append(cell)
return(data)