def get_volumes_usage(session): response = session.get('https://mslnrcorpsan3/api/1.8/volume?space=true', verify=False) results = json.loads(response.text) output = CustomSensorResult("Array real usage per volume") for item in results: output.add_channel(channel_name=item['name'], unit="Bytes", value=item['total']) print(output.get_json_result())
def get_manual_snapshots(session): response = session.get( 'https://mslnrcorpsan3/api/1.8/volume?snap=true&space=true', verify=False) results = json.loads(response.text) output = CustomSensorResult("List of manually created snapshots") for item in results: if ("Daily" not in item['name']): output.add_channel(channel_name=item['name'], unit="Bytes", value=item['snapshots'], is_limit_mode=True, limit_max_warning=100000000000, limit_warning_msg="Snapshot size too large") print(output.get_json_result())
def get_controllers(session): output = CustomSensorResult("Pure storage controllers") response = session.get( 'https://mslnrcorpsan3/api/1.8/array?controllers=true', verify=False) results = json.loads(response.text) for item in results: if item['status'] == 'ready': output.add_channel( channel_name=item['mode'], value=0, value_lookup="prtg.standardlookups.purestorage.hardwarestatus") else: output.add_channel( channel_name=item['mode'], value=10, value_lookup="prtg.standardlookups.purestorage.hardwarestatus") print(output.get_json_result())
def get_volumes_rw(session): response = session.get('https://mslnrcorpsan3/api/1.8/volume?space=true', verify=False) results = json.loads(response.text) output = CustomSensorResult("Volumes RW performance") for item in results: query = 'https://mslnrcorpsan3/api/1.8/volume' + '/' + item[ 'name'] + '?action=monitor' new_response = session.get(query, verify=False) new_results = json.loads(new_response.text) output.add_channel(channel_name=item['name'] + ' Read B/s', unit="BytesBandwidth", value=new_results[0]['input_per_sec']) output.add_channel(channel_name=item['name'] + ' Write B/s', unit="BytesBandwidth", value=new_results[0]['output_per_sec']) print(output.get_json_result())
def get_hardware(session): output = CustomSensorResult("Pure storage hardware") response = session.get('https://mslnrcorpsan3/api/1.8/hardware', verify=False) results = json.loads(response.text) for item in results: if item['status'] == 'ok' and ('FAN' in item['name'] or 'PWR' in item['name'] or 'FC' in item['name']): output.add_channel( channel_name=item['name'], value=0, value_lookup="prtg.standardlookups.purestorage.hardwarestatus") elif item['status'] != 'ok' and ('FAN' in item['name'] or 'PWR' in item['name'] or 'FC' in item['name']): output.add_channel( channel_name=item['name'], value=10, value_lookup="prtg.standardlookups.purestorage.hardwarestatus") print(output.get_json_result())
def BlockChainTimeStamp(pdata): params = json.loads(pdata['params']) url = "http://" + pdata['host'] + ":" + str(params['port']).rstrip( ) + "/api/blocks/?limit=1&offset=0&orderBy=height:desc" before = datetime.datetime.now() response = urlopen(url) data = json.loads(response.read().decode('utf8')) timestamp = data['blocks'][0]['timestamp'] height = data['blocks'][0]['height'] uptime = (datetime.datetime.now() - datetime.datetime(2016, 5, 24, 13, 00, 00)).total_seconds() timer = 0 after = datetime.datetime.now() final = after - before if is_dst(str(params['tz'])) == True: timer = ((datetime.datetime.now() - datetime.datetime(2016, 5, 24, 13, 00, 00)).total_seconds() - timestamp) else: timer = ((datetime.datetime.now() - datetime.datetime(2016, 5, 24, 13, 00, 00)).total_seconds() - timestamp) if time.localtime().tm_isdst == 0: timer = timer + 3600 result = CustomSensorResult('Block Chain Status') result.add_channel(channel_name="Block Age", unit="Custom", value=timer, is_float=False, is_limit_mode=True, primary_channel=True) result.add_channel(channel_name="Block Height", unit="Custom", value=height, is_float=False, is_limit_mode=True) return result.get_json_result()
def main(argv): is_new_cookie = False switch_ip = "192.168.0.2" switch_password = "******" switch_cookie = "" port_number = 0 # Get PRTG parameters try: # Load from PRTG JSON prtg = json.loads(argv[0]) params = str.split(prtg['params']) # Decode the arguments opts, args = getopt.getopt(params, "hi:p:n:", [ "port=", "ip=", "password="******"No arguments found.")) exit() # Port number elif opt in ("-n", "--port"): port_number = int(arg) # We assume port given is human, not binary. Just in case if port_number > 0: port_number -= 1 elif opt in ("-p", "--password"): switch_password = str(arg) elif opt in ("-i", "--ip"): switch_ip = str(arg) except json.JSONDecodeError as err: result = CustomSensorResult() result.add_error(("No arguments provided." + err.msg)) print(result.get_json_result()) exit(1) except getopt.GetoptError as err: result = CustomSensorResult() result.add_error(("Incorrect syntax." + err.msg)) exit(2) # Check if we have a stored cookie file try: f = open(cookie_dir + '/.gs108ecookie' + switch_ip, 'r') switch_cookie_name = f.readline().rstrip('\n') switch_cookie_content = f.readline().rstrip('\n') f.close() if check_login_cookie_valid(switch_ip, switch_cookie_name, switch_cookie_content) is False: raise IOError except IOError: # File doesn't exist. Get login key is_new_cookie = True switch_cookie_name, switch_cookie_content = get_login_cookie( switch_ip, switch_password) if switch_cookie_name is None: result = CustomSensorResult() result.add_error(("Cookie jar is empty. Dir:" + cookie_dir)) print(result.get_json_result()) exit(1) f = open(cookie_dir + '/.gs108ecookie' + switch_ip, 'w') f.write(switch_cookie_name + "\n") f.write(switch_cookie_content + "\n") f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())) f.close() # Set up our cookie jar jar = requests.cookies.RequestsCookieJar() jar.set(switch_cookie_name, switch_cookie_content, domain=switch_ip, path='/') # Get the port stats page url = 'http://' + switch_ip + '/portStatistics.cgi' page = requests.get(url, cookies=jar) start_time = time.perf_counter() tree = html.fromstring(page.content) # Scrape the data if (switch_cookie_name == "SID"): # GS105Ev2 format (no element names!) rx1 = tree.xpath('//tr[@class="portID"]//input[@type="hidden"][2]') tx1 = tree.xpath('//tr[@class="portID"]/input[@type="hidden"][4]') crc1 = tree.xpath('//tr[@class="portID"]/input[@type="hidden"][6]') else: # GS108Ev3 format rx1 = tree.xpath('//tr[@class="portID"]/input[@name="rxPkt"]') tx1 = tree.xpath('//tr[@class="portID"]/input[@name="txpkt"]') crc1 = tree.xpath('//tr[@class="portID"]/input[@name="crcPkt"]') # Hold fire time.sleep(sleep_time) # Get the port stats page again! We need to compare two points in time page = requests.get(url, cookies=jar) end_time = time.perf_counter() tree = html.fromstring(page.content) # Scrape the data if (switch_cookie_name == "SID"): # GS105Ev2 format (no element names!) rx2 = tree.xpath('//tr[@class="portID"]//input[@type="hidden"][2]') tx2 = tree.xpath('//tr[@class="portID"]/input[@type="hidden"][4]') crc2 = tree.xpath('//tr[@class="portID"]/input[@type="hidden"][6]') else: # GS108Ev3 format rx2 = tree.xpath('//tr[@class="portID"]/input[@name="rxPkt"]') tx2 = tree.xpath('//tr[@class="portID"]/input[@name="txpkt"]') crc2 = tree.xpath('//tr[@class="portID"]/input[@name="crcPkt"]') sample_time = end_time - start_time sample_factor = 1 / sample_time # print("It took us " + str(sample_time) + " seconds.") # Test code, print all values. # for i in range(0, len(tx2)): # # Convert Hex to Int, get bytes traffic # port_traffic = int(tx2[i].value, 16) - int(tx1[i].value, 16) # port_speed_bps = port_traffic * sample_factor # print("Port " + str(i) + ": " + "{0:.2f}".format(port_speed_bps/1024, ) + "kbps.") if (switch_cookie_name == "SID"): # GS105Ev2 # Values are already in Int port_traffic_rx = int(rx2[port_number].value, 10) - int( rx1[port_number].value, 10) port_traffic_tx = int(tx2[port_number].value, 10) - int( tx1[port_number].value, 10) port_traffic_crc_err = int(crc2[port_number].value, 10) - int( crc2[port_number].value, 10) port_speed_bps_rx = port_traffic_rx * sample_factor port_speed_bps_tx = port_traffic_tx * sample_factor port_name = "Port " + str(port_number) else: # GS108Ev3 format # Convert Hex to Int, get bytes traffic port_traffic_rx = int(rx2[port_number].value, 16) - int( rx1[port_number].value, 16) port_traffic_tx = int(tx2[port_number].value, 16) - int( tx1[port_number].value, 16) port_traffic_crc_err = int(crc2[port_number].value, 16) - int( crc2[port_number].value, 16) port_speed_bps_rx = port_traffic_rx * sample_factor port_speed_bps_tx = port_traffic_tx * sample_factor port_name = "Port " + str(port_number) # Use paepy to form a meaningful response for PRTG. result = AdvancedCustomSensorResult() result.add_channel("Traffic In", unit="BytesBandwidth", value=port_speed_bps_rx, is_float=False, speed_size="KiloBytes") result.add_channel("Traffic Out", unit="BytesBandwidth", value=port_speed_bps_tx, is_float=False, speed_size="KiloBytes") result.add_channel("CRC Errors", unit="CRC Errors", value=port_traffic_crc_err) result.add_channel("Response Time", unit="TimeResponse", value=sample_time * 1000, is_float=True) # Print the result print(result.get_json_result())
#Turn status colour into a number so that it can be viewed in prtg if output['status'] == 'green': status = 0 elif output['status'] == 'yellow': status = 1 elif output['status'] == 'red': status = 2 #turn timed out into a number so that it can be viewed in prtg if output['timed_out'] == False: timedOut = 0 else: timedOut = 1 #create a prtg sensor and add the channel data. Each key/value in the json response from ES gets channelised sensor = CustomSensorResult(output['status']) sensor.add_channel(channel_name="Status", unit="Count", value=status, is_limit_mode=True, limit_max_error=1.5, limit_max_warning=0.5) sensor.add_channel(channel_name="Number Of Data Nodes", unit="Count", value=output['number_of_data_nodes']) sensor.add_channel(channel_name="Number of Nodes", unit="Count", value=output['number_of_nodes']) sensor.add_channel(channel_name="Percent of Shards Active", unit="Percent", value=output['active_shards_percent_as_number'])
else: servername = server['hostname'] protocol = 'https' url = protocol + '://' + servername + port + url_path try: response = urlopen(url) data = json.loads(response.read().decode('utf8')) if data['success'] == True and data['enabled'] == True: ret = True break except: pass # create sensor result if ret == True: result = CustomSensorResult("Forging Status Active") # add primary channel result.add_channel(channel_name="Forging Status", unit="Custom", value=1, is_float=False, is_limit_mode=True, primary_channel=True) else: result = CustomSensorResult("Forging Disable") result.add_channel(channel_name="Forging Status", unit="Custom", value=0, is_float=False, is_limit_mode=True, primary_channel=True)
if b'Load' in d: Load = {'cpu': d.split()[2]} Tmem = 0 Fmem = 0 for m in meminfo: if b'MemTotal' in m: Tmem = m.split()[1] if b'MemFree' in m: Fmem = m.split()[1] #print(nm) # create sensor result result = CustomSensorResult( "NE health monitoring on: {0} RAM: {1:.2f} MB; Uptime:{2}Hrs {3}Min". format(ip, int(Tmem) / 1024, int(uptime) // 3600, (int(uptime) % 3600) // 60)) # add primary channel result.add_channel(channel_name="CPU load", unit=" ", value=Load['cpu'], is_float=True, primary_channel=True, is_limit_mode=True, limit_min_error=0, limit_max_error=10, limit_error_msg="Percentage too high", decimal_mode='Auto')
# ########################## import requests import sys, json from math import log10 from paepy.ChannelDefinition import CustomSensorResult data = {"host": "172.25.25.31", "params": "MSACFP"} data = json.loads(sys.argv[1]) ip = data['host'] objs = data['params'].split() if len(objs) == 0: result = CustomSensorResult() result.add_error( "Parameters_required = CFP_Objects seperated space, max 25 eg: MSACFP or MSACFP-1-11-511 MSACFP-1-10-505 (@ Additional Parameters while adding sensor)" ) print(result.get_json_result()) sys.exit(-1) cfplist = '%0A'.join(objs) def NeSession(): try: session = requests.Session() session.auth = ('DIAGUSER', 'j72e#05t') session.headers.update({"Cookie": "LOGIN_LEVEL=2; path=/;"}) return session
hostname = conn.snmpget('1.3.6.1.4.1.12356.101.13.2.1.1.11.1') for p in hostname.keys(): device[i].update({'hostname': str(p)}) # get ifOperstatus for all interfaces for p in device[i]['int'].keys(): ifstatus = conn.snmpget('1.3.6.1.2.1.2.2.1.8' + "." + device[i]['int'][p]['ifindex']) for k, v in ifstatus.items(): device[i]['int'][p].update({'ifstatus': str(k)}) # create interface list from sensor additional parameters iflist = params['params'] # create PRTG sensor channels result = CustomSensorResult("Result from FortiGate Sensor " + params['host']) for i in device: for k in device[i]['int'].keys(): cname = device[i]['hostname'] + " " + k if findWholeWord(k)(iflist) is not None: if k == 'wan1' and device[i]['clIndex'] == '1': result.add_channel( channel_name=cname, value=device[i]['int'][k]['ifstatus'], value_lookup='custom.lookup.forti.interfaces', primary_channel=True) else: result.add_channel( channel_name=cname, value=device[i]['int'][k]['ifstatus'], value_lookup='custom.lookup.forti.interfaces')
if Unit == "MBps": TX = (TX / 1000000) / T RX = (RX / 1000000) / T else: RX = (RX * 8 / 1000000) / T TX = (TX * 8 / 1000000) / T return TX, RX try: tx, rx = getSpeed() # create sensor result result = CustomSensorResult("BandWith Monitor @ {0} {1}".format( ip, object_name)) result.add_channel(channel_name='Total', unit=Unit, value=format(float(tx + rx), '.2f'), is_float=True, decimal_mode='Auto') result.add_channel(channel_name='TX', unit=Unit, value=format(float(tx), '.2f'), is_float=True, decimal_mode='Auto') result.add_channel(channel_name='RX', unit=Unit, value=format(float(rx), '.2f'), is_float=True, decimal_mode='Auto')
getDifferences() def printArrMultipleValues(): for i in range(0, len(arrMultipleValues)): print("Port: " + str(i + 1)) #print(arrMultipleValues[i]) print("In-Speed: " + str(getInSpeed(i))) print("Out-Speed: " + str(getOutSpeed(i))) print("In-Speed: " + str(getInSpeedTotal(i))) print("Out-Speed: " + str(getOutSpeedTotal(i))) ping_result = doPing() result = CustomSensorResult("OK") result.add_channel(channel_name="Pingzeit", unit="ms", value=ping_result.result["avg_time"], is_float=True, primary_channel=True, is_limit_mode=True, limit_min_error=0, limit_max_error=250, limit_error_msg="Percentage too high") result.add_channel(channel_name="Temparatur", unit="°C", value=tempValue, is_float=False,
import json import pymssql import datetime deviceID = 8 if __name__ == "__main__": conn = pymssql.connect(server='10.0.0.55', user='******', password='******', database='SystemMonitor') cursor = conn.cursor() endDate = datetime.datetime.now() startDate = endDate - datetime.timedelta(0, 120) cursor.execute("SELECT * FROM DeviceInfo WHERE DeviceID = '" + str(deviceID) + "' AND UpdateTime BETWEEN '" + startDate.strftime("%Y/%m/%d %H:%M:%S") + "' AND '" + endDate.strftime("%Y/%m/%d %H:%M:%S") + "'") row = cursor.fetchone() cpu = json.loads(row[2]) result = CustomSensorResult("this sensor is kevin's test") conn.close() for i in range(len(cpu['usage_rate'])): print(cpu['usage_rate'][i]) result.add_channel(channel_name="Processor" + str(i), unit="Percent", value=cpu['usage_rate'][i], is_float=True) print(result.get_json_result())
import sys import json import purestorage import urllib3 # get CustomSensorResult from paepy package from paepy.ChannelDefinition import CustomSensorResult if __name__ == "__main__": # interpret first command line parameter as json object data = json.loads(sys.argv[1]) # create sensor result params = json.loads(data['params']) result = CustomSensorResult("Pure Storage performance info") urllib3.disable_warnings() # get basic statistics from the FlashArray specified in the json object fa = purestorage.FlashArray(params['addr'], api_token=params['api_token']) fainfo = fa.get(action='monitor') fa.invalidate_cookie() # add primary channel result.add_channel(channel_name="wr sec", unit="IOPS write", value=fainfo[0]['writes_per_sec'], primary_channel=True) # add additional channels result.add_channel(channel_name="rd sec", unit="IOPS read", value=fainfo[0]['reads_per_sec'])
def printOut(message, upsens, downsens, warnsens, downacksens, partialdownsens, unusualsens, pausedsens, undefinedsens): # Building sensor's output (channels) result = CustomSensorResult(message) result.add_channel(channel_name="Up ", unit="Count", value=checkValue(upsens)) result.add_channel(channel_name="Down ", unit="Count", value=checkValue(downsens)) result.add_channel(channel_name="Warning", unit="Count", value=checkValue(warnsens)) result.add_channel(channel_name="Down Ack", unit="Count", value=checkValue(downacksens)) result.add_channel(channel_name="Partial Down", unit="Count", value=checkValue(partialdownsens)) result.add_channel(channel_name="Unusual", unit="Count", value=checkValue(unusualsens)) result.add_channel(channel_name="Paused", unit="Count", value=checkValue(pausedsens)) result.add_channel(channel_name="Undefined", unit="Count", value=checkValue(undefinedsens)) print(result.get_json_result())
def printError(msg): result = CustomSensorResult() result.add_error(msg) print(result.get_json_result()) sys.exit(-1)
try: data = json.loads(sys.argv[1]) except: data = {"host":"172.25.23.34","params":"SFP-1-1-1:-Distance,-Wavelength;SFP-1-2-1:-SI,-Distance"} ip = data['host'] username = data.get('linuxloginusername', 'DIAGUSER') password = data.get('linuxloginpassword', 'j72e#05t') if len(req_obj) == 0: result = CustomSensorResult() result.add_error("Parameters_required = Objects seperated by ';' and attributes seperated by ',' : object_name1:Attribute1,Attribute2;object_name2:Attribute3,Attribute4 (@ Additional Parameters while adding sensor)") print(result.get_json_result()) sys.exit(-1) req_obj={} if len(data["params"]): a1=data['params'].split(';') for i in a1: a=i.split(':') req_obj[a[0]]=a[1].split(',') def NeSession():
voter_url = protocol + '://' + servername + port + url_voters try: response = urlopen(url) found_response = urlopen(found_url) voter_response = urlopen(voter_url) data = json.loads(response.read().decode('utf8')) found_data = json.loads(found_response.read().decode('utf8')) voter_data = json.loads(voter_response.read().decode('utf8')) if data['success'] == True and found_data['success'] == True: ret = True break except: pass if ret == True: vvalue = 0 for vv in voter_data['accounts']: vvalue = vvalue + int(vv['balance']) result = CustomSensorResult("Forging Productivity") # add primary channel result.add_channel(channel_name="Forging Productivity", unit="Custom", value=data['delegate']['productivity'], is_float=True, is_limit_mode=True, primary_channel=True) result.add_channel(channel_name="Forging ProducedBlocks", unit="Custom", value=data['delegate']['producedblocks'], is_float=False, is_limit_mode=True, primary_channel=False) result.add_channel(channel_name="Forging MissedBlocks", unit="Custom", value=data['delegate']['missedblocks'], is_float=False, is_limit_mode=True, primary_channel=False) result.add_channel(channel_name="Forging Approval", unit="Custom", value=data['delegate']['approval'], is_float=True, is_limit_mode=True, primary_channel=False) result.add_channel(channel_name="Forging Found", unit="Custom", value=int(found_data['balance'])/100000000, is_float=True, is_limit_mode=True, primary_channel=False) result.add_channel(channel_name="Forging Rate", unit="Custom", value=data['delegate']['rate'], is_float=False, is_limit_mode=False, primary_channel=False) result.add_channel(channel_name="Voters Count", unit="Custom", value=len(voter_data['accounts']), is_float=False, is_limit_mode=False, primary_channel=False) result.add_channel(channel_name="Voters Found", unit="Custom", value=vvalue/100000000, is_float=True, is_limit_mode=True, primary_channel=False) print(result.get_json_result())
user='******', password='******', database='SystemMonitor') cursor = conn.cursor() endDate = datetime.datetime.now() startDate = endDate - datetime.timedelta(0, 180) cursor.execute("SELECT * FROM DeviceInfo WHERE DeviceID = '" + str(deviceID) + "' AND UpdateTime BETWEEN '" + startDate.strftime("%Y/%m/%d %H:%M:%S") + "' AND '" + endDate.strftime("%Y/%m/%d %H:%M:%S") + "'") tempRow = cursor.fetchone() while tempRow: row = tempRow tempRow = cursor.fetchone() cpu = json.loads(row[2]) result = CustomSensorResult("CPU Info") conn.close() for i in range(len(cpu['usage_rate'])): print(cpu['usage_rate'][i]) result.add_channel(channel_name="Processor" + str(i), unit="Percent", value=cpu['usage_rate'][i], is_float=True, is_limit_mode=True, limit_max_error=80, limit_error_msg="使用率偏高") print(result.get_json_result())
import requests import json import configparser from paepy.ChannelDefinition import CustomSensorResult def jprint(obj): # create a formatted string of the Python JSON object text = json.dumps(obj, sort_keys=True, indent=4) print(text) configlocation = r"C:\Program Files (x86)\PRTG Network Monitor\Custom Sensors\EXEXML\Ruckus_Wlan_Clients.ini" configfile = configparser.ConfigParser() configfile.read(configlocation) result = CustomSensorResult() # Parameters cookie = requests.Session() username = configfile["credentials"]["username"] password = configfile["credentials"]["password"] # Disable warnings, needs to be removed if valid certificate is in place. requests.packages.urllib3.disable_warnings() # Start Session para_session = {"username": username, "password": password} urlsession = "https://vsz.ant.int.infrastay.be:8443/wsg/api/public/v8_2/session" session = cookie.post(urlsession, json=para_session, verify=False) # Get session Info # call = cookie.get(urlsession, verify=False)
import paramiko import sys, json import re from paepy.ChannelDefinition import CustomSensorResult from time import sleep, time data = {"host": "172.25.101.11", "params": "172.25.101.106"} data = json.loads(sys.argv[1]) serverip = data['host'] dbserverip = data['params'] if not dbserverip: result = CustomSensorResult() result.add_error( "@ Additional Parameters while adding sensor, enter DBserverIP") print(result.get_json_result()) sys.exit(-1) port = 22 username = '******' password = '******' def execute_ssh(command, raw=0): stdin, stdout, stderr = ssh.exec_command(command) data = stdout.read().decode('utf-8') if raw: return data return data.strip().splitlines()
import urllib.request import urllib.error from paepy.ChannelDefinition import CustomSensorResult data = json.loads(sys.argv[1]) host = data['host'] apiKey = str(data['params']) url = 'https://api.shodan.io/shodan/host/{h}?key={k}'.format(h=host, k=apiKey) with urllib.request.urlopen(url) as res: raw = res.read() hostData = json.loads(raw.decode('ascii')) portsStr = " ".join([str(p) for p in hostData['ports']]) msg = "Open Ports: " + portsStr sensor = CustomSensorResult(msg) sensor.add_channel('Open Ports', value=len(hostData['ports']), unit='ports') if 'vulns' in hostData.keys(): sensor.add_channel('Vulnerabilities', value=len(hostData['vulns']), unit='vulns', is_limit_mode=True, limit_max_error=0) else: sensor.add_channel('Vulnerabilities', value=0, unit='vulns', is_limit_mode=True, limit_max_error=0)
#!..\..\redist\Python34 # -*- coding: utf-8 -*- from paepy.ChannelDefinition import CustomSensorResult import sys import json import pymssql import datetime deviceID = 12 if __name__ == "__main__": conn = pymssql.connect(server='10.0.0.55', user='******', password='******', database='SystemMonitor') cursor = conn.cursor() endDate = datetime.datetime.now() startDate = endDate - datetime.timedelta(0, 180) cursor.execute("SELECT * FROM DeviceInfo WHERE DeviceID = '" + str(deviceID) + "' AND UpdateTime BETWEEN '" + startDate.strftime("%Y/%m/%d %H:%M:%S") + "' AND '" + endDate.strftime("%Y/%m/%d %H:%M:%S") + "'") tempRow = cursor.fetchone() while tempRow: row = tempRow tempRow = cursor.fetchone() network = json.loads(row[5]) result = CustomSensorResult("this sensor is kevin's test") conn.close() result.add_channel(channel_name="使用率", unit="kbit", value=network['usage']/1024.*8, is_float=True) result.add_channel(channel_name="接收", unit="kbit", value=network['receive']/1024.*8, is_float=True) result.add_channel(channel_name="傳送", unit="kbit", value=network['send']/1024.*8, is_float=True) print(result.get_json_result())
req = requests.get(url) #load the json response into a dictionary output = json.loads(req.text) #Turn status colour into a number so that it can be viewed in prtg color = output['status']['overall']['state'] if color == 'green': status = 0 elif color == 'yellow': status = 1 elif color == 'red': status = 2 # create a prtg sensor and add the channel data. Each key/value in the json response from ES gets channelised sensor = CustomSensorResult(output['status']['overall']['state']) sensor.add_channel(channel_name="Status", unit="Count", value=status, is_limit_mode=True, limit_max_error=1.5, limit_max_warning=0.5) sensor.add_channel(channel_name="Metrics Requests Total", unit="Count", value=output['metrics']['requests']['total']) sensor.add_channel(channel_name="Metrics Connections", unit="Count", value=output['metrics']['concurrent_connections']) sensor.add_channel( channel_name="Max. Response Time", unit="Milliseconds",
# -*- coding: utf-8 -*- from paepy.ChannelDefinition import CustomSensorResult import sys import json import pymssql import datetime deviceID = 12 if __name__ == "__main__": conn = pymssql.connect(server='10.0.0.55', user='******', password='******', database='SystemMonitor') cursor = conn.cursor() endDate = datetime.datetime.now() startDate = endDate - datetime.timedelta(0, 180) cursor.execute("SELECT * FROM DeviceInfo WHERE DeviceID = '" + str(deviceID) + "' AND UpdateTime BETWEEN '" + startDate.strftime("%Y/%m/%d %H:%M:%S") + "' AND '" + endDate.strftime("%Y/%m/%d %H:%M:%S") + "'") tempRow = cursor.fetchone() while tempRow: row = tempRow tempRow = cursor.fetchone() disk = json.loads(row[4]) result = CustomSensorResult("this sensor is kevin's test") conn.close() for diskInfo in disk: result.add_channel(channel_name=diskInfo['name'] + " 使用率", unit="Percent", value=diskInfo['usage_rate'], is_float=True, is_limit_mode=True, limit_max_error=80, limit_error_msg="剩餘空間不足") result.add_channel(channel_name=diskInfo['name'] + " 剩餘", unit="GByte", value=diskInfo['free'], is_float=True) result.add_channel(channel_name=diskInfo['name'] + " 共", unit="GByte", value=diskInfo['total'], is_float=True) print(result.get_json_result())
connection.write(supassword + b" \n") router_output = connection.read_until(b">", reading_timeout) connection.write( b"/usr/sbin/tejas/fpga_scripts/temsense.sh | grep 'Read value' \n") fpgadata = connection.read_until(b">", reading_timeout) if b'Value of offset' not in fpgadata: connection.write( b"/usr/sbin/tejas/fpga_scripts/temsense_6.sh | grep 'Read value' \n") fpgadata = connection.read_until(b">", reading_timeout) connection.close() if b'Value of offset' not in fpgadata: result = CustomSensorResult() result.add_error( "Sorry!, the node might not support to view FPGA temperature") print(result.get_json_result()) sys.exit(-1) fpgadata = [fa for fa in fpgadata.splitlines() if b"Value of offset" in fa] result = CustomSensorResult("FPGA temperature monitoring @: {}".format(ip)) for fno, fpga in enumerate(fpgadata): temp = eval(fpga.split(b"=")[1].split()[0]) - eval('0x180') result.add_channel(channel_name="FPGA_" + str(fno + 1), unit="Temperature", value=temp, decimal_mode='Auto')
#!..\..\redist\Python34 # -*- coding: utf-8 -*- from paepy.ChannelDefinition import CustomSensorResult import sys import json import pymssql import datetime deviceID = 15 if __name__ == "__main__": conn = pymssql.connect(server='10.0.0.55', user='******', password='******', database='SystemMonitor') cursor = conn.cursor() endDate = datetime.datetime.now() startDate = endDate - datetime.timedelta(0, 180) cursor.execute("SELECT * FROM DeviceInfo WHERE DeviceID = '" + str(deviceID) + "' AND UpdateTime BETWEEN '" + startDate.strftime("%Y/%m/%d %H:%M:%S") + "' AND '" + endDate.strftime("%Y/%m/%d %H:%M:%S") + "'") tempRow = cursor.fetchone() while tempRow: row = tempRow tempRow = cursor.fetchone() memory = json.loads(row[3]) result = CustomSensorResult("this sensor is kevin's test") conn.close() result.add_channel(channel_name="使用率", unit="Percent", value=memory['usage_rate'], is_float=True) result.add_channel(channel_name="free", unit="GByte", value=memory['free'], is_float=True) result.add_channel(channel_name="total", unit="GByte", value=memory['total'], is_float=True) print(result.get_json_result())
#!..\..\redist\Python34 # -*- coding: utf-8 -*- from paepy.ChannelDefinition import CustomSensorResult import sys import json if __name__ == "__main__": data = json.loads(sys.argv[1]) result = CustomSensorResult("this sensor is added to " + data['host']) result.add_channel(channel_name="percentage", unit="Percent", value=87, is_float=False, primary_channel=True, is_limit_mode=True, limit_min_error=10, limit_max_error=90, limit_error_msg="percentage too high") result.add_channel(channel_name="response time", unit="TimeResponse", value="4711") print(result.get_json_result())