def pollDownstreamDocsisChannels(olt_name, ip_address, community): session = Session(hostname=ip_address, community=community, version=2, use_numeric=True) docsis_channels = docsisChannels() downstream_initial_index = 2013798400 finishLoop = False while (finishLoop == False): oids = [] oids.append('IF-MIB::ifDescr.' + str(downstream_initial_index)) oids.append('IF-MIB::ifAdminStatus.' + str(downstream_initial_index)) oids.append('.1.3.6.1.2.1.10.127.1.1.1.1.2.' + str(downstream_initial_index)) #Frequency docsis_channel_stats = session.get_bulk( oids, non_repeaters=0, max_repetitions=snmp_max_repetitions) for item in docsis_channel_stats: downstream_initial_index = int(item.oid_index) if downstream_initial_index >= 4194312192: #print("Finishing loop, upstream_initial_index = " + str(upstream_initial_index)) finishLoop = True break if item.oid == '.1.3.6.1.2.1.2.2.1.2': #ifDescr if "docsCableDownstream" in item.value: docsis_channels.downstream_channel[ item.oid_index] = docsisChannel(str(item.value)) docsis_channels.downstream_channel[ item.oid_index].ifDescr = str(item.value) #redundancy? elif item.oid == '.1.3.6.1.2.1.2.2.1.7': #ifAdminStatus if item.oid_index in docsis_channels.downstream_channel: docsis_channels.downstream_channel[ item.oid_index].setStatus(str(item.value)) elif '.1.3.6.1.2.1.10.127.1.1.1.1.2' in item.oid: #Frequency #print("upstream_initial_index = " + str(upstream_initial_index)) if item.oid_index in docsis_channels.downstream_channel: docsis_channels.downstream_channel[ item.oid_index].setFrequency(int(item.value)) for downstream_channel in docsis_channels.downstream_channel: channel_frequency = docsis_channels.downstream_channel[ downstream_channel].frequency if channel_frequency == 0: continue print(olt_name + "," + docsis_channels.downstream_channel[downstream_channel].ifDescr + "," + str(docsis_channels.downstream_channel[downstream_channel]. frameid) + "," + str(docsis_channels.downstream_channel[downstream_channel]. channelid) + "," + str(channel_frequency) + "," + docsis_channels.downstream_channel[downstream_channel].status)
class SNMPBus(object): SNMP_VARIABLES = SNMP_VARIABLES def __init__(self, ip, community): self.var_oid, self.var_name, self.callable = list(), list(), list() for k, v, c in self.SNMP_VARIABLES: self.var_oid.append(k) self.var_name.append(v) self.callable.append(c) self.var_oid = tuple(self.var_oid) self.var_name = tuple(self.var_name) self.callable = tuple(self.callable) self._dict = dict() self.session = Session(hostname=ip, community=community, version=2) self._device_update = "snmpbulkget -v 2c -c {0} {1} .1.3.6.1.2.1.25.2.3.1.3 .1.3.6.1.2.1.25.2.3.1.4 .1.3.6.1.2.1.25.2.3.1.5 .1.3.6.1.2.1.25.2.3.1.6 | awk '!a[$0]++' | grep 'hrStorageUsed\|hrStorageSize\|hrStorageAllocationUnits\|hrStorageDescr'".format( community, ip) def __getitem__(self, item): if item in self._dict: return self._dict[item] def __setitem__(self, key, value): self._dict[key] = value def _checkout_variables(self, varlist): _varlist = list() _varname = list() _callable = list() for var in varlist: if var in self.var_name: i = self.var_name.index(var) _varlist.append(var) _varname.append(self.var_name[i]) _callable.append(self.callable[i]) return _varlist, _varname, _callable def _gen_default_variables(self): return list(self.var_oid), list(self.var_name), list(self.callable) def update(self, varlist=None): if not varlist: varlist, varname, call = self._gen_default_variables() else: varlist, varname, call = self._checkout_variables(varlist) data = self.session.get_bulk(varlist, 1, 1) #print "data: ",data #print data[11] for i in range(len(data)): d = str(data[i]).split(' ')[1].split('=')[1].strip("'") if not callable(call[i]): print 'varname', varname[i], ':', d self.__setitem__(varname[i], d) else: self.__setitem__(varname[i], call[i](d)) def update_devices(self): _d = dict() data = commands.getoutput(self._device_update).split('\n') while data: _desc = data.pop(0).split('=')[1].split(':')[1].strip() _d[_desc] = dict() _unit = data.pop(0).split('=')[1].split(':')[1].strip() _d[_desc]['unit'] = _unit _size = data.pop(0).split('=')[1].split(':')[1].strip() _d[_desc]['size'] = _size _used = data.pop(0).split('=')[1].split(':')[1].strip() _d[_desc]['used'] = _used return _d
def pollDocsisChannels(olt_name, ip_address, community): session = Session(hostname=ip_address, community=community, version=2, use_numeric=True) docsis_channels = docsisChannels() upstream_initial_index = 1980243960 finishLoop = False while (finishLoop == False): oids = [] set_oids = [] oids.append('IF-MIB::ifDescr.' + str(upstream_initial_index)) oids.append('IF-MIB::ifAdminStatus.' + str(upstream_initial_index)) oids.append('.1.3.6.1.2.1.10.127.1.1.2.1.2.' + str(upstream_initial_index)) #Frequency docsis_channel_stats = session.get_bulk( oids, non_repeaters=0, max_repetitions=snmp_max_repetitions) current_frame = 0 for item in docsis_channel_stats: upstream_initial_index = int(item.oid_index) if upstream_initial_index >= 2013798401: #print("Finishing loop, upstream_initial_index = " + str(upstream_initial_index)) finishLoop = True break if item.oid == '.1.3.6.1.2.1.2.2.1.2': #ifDescr if "docsCableUpstream" in item.value: docsis_channels.upstream_channel[ item.oid_index] = docsisChannel(str(item.value)) docsis_channels.upstream_channel[ item.oid_index].ifDescr = str(item.value) #redundancy? elif item.oid == '.1.3.6.1.2.1.2.2.1.7': #ifAdminStatus if item.oid_index in docsis_channels.upstream_channel: docsis_channels.upstream_channel[item.oid_index].setStatus( str(item.value)) elif '.1.3.6.1.2.1.10.127.1.1.2.1.2' in item.oid: #Frequency #print("upstream_initial_index = " + str(upstream_initial_index)) if item.oid_index in docsis_channels.upstream_channel: docsis_channels.upstream_channel[ item.oid_index].setFrequency(int(item.value)) current_frame = docsis_channels.upstream_channel[ item.oid_index].frameid ipAndFrame = ip_address + "," + current_frame if ipAndFrame not in filter_list: #print("-----Frequency: " + str(int(item.value))) if int(item.value) in disUpFreq and int( item.value) > 0: set_oids.append( ('.1.3.6.1.2.1.2.2.1.7' + "." + str(item.oid_index), 2, 'INTEGER')) if len(set_oids) > 0: setValue(set_oids, ip_address, community) for upstream_channel in docsis_channels.upstream_channel: channel_frequency = docsis_channels.upstream_channel[ upstream_channel].frequency if channel_frequency == 0: continue print( olt_name + "," + docsis_channels.upstream_channel[upstream_channel].ifDescr + "," + str(docsis_channels.upstream_channel[upstream_channel].frameid) + "," + str(docsis_channels.upstream_channel[upstream_channel].channelid) + "," + str(channel_frequency) + "," + docsis_channels.upstream_channel[upstream_channel].status)
for item in data: for attribute, value in item.iteritems(): if attribute != 'time': z.addData(host, attribute, value, timestamp) results = z.sendData() if __name__ == "__main__": """Using SNMP-Bulk-Request to fetch all data into one Request""" session = Session(hostname='10.0.0.22', community='public', version=2) try: oid_list = [ '.1.3.6.1.4.1.8072.9999.9999.1', '.1.3.6.1.4.1.8072.9999.9999.2' ] response_snmp = session.get_bulk(oid_list, 200, 200) #Iterate through SNMP-Response and push data to zabbix-sender, which will transmitt the data to zabbix for item in response_snmp: #Check for status data if item.oid == 'iso.3.6.1.4.1.8072.9999.9999.1': push_status_data_to_zabbix(json.loads(str(item.value)), 'monitoring_client_1') else: push_sensor_data_to_zabbix(json.loads(str(item.value)), 'monitoring_client_1') print 0 except: print 1
def a5(): session1 = Session(hostname='10.40.40.194', community='public', version=2) session2 = Session(hostname='10.40.40.198', community='public', version=2) number1 = session1.get('ifNumber.0') number2 = session2.get('ifNumber.0') in_tot_s = 0 out_tot_s = 0 temp1_s = 0 temp2_s = 0 temp3_s = 0 temp4_s = 0 in_tot_r = 0 out_tot_r = 0 temp1_r = 0 temp2_r = 0 temp3_r = 0 temp4_r = 0 inUpac_s = session1.get_bulk("ifInUcastPkts", 0, int(number1.value)) for i in inUpac_s: temp1_s = temp1_s + int(i.value) inNUpac_s = session1.get_bulk("ifInNUcastPkts", 0, int(number1.value)) for i in inNUpac_s: temp2_s = temp2_s + int(i.value) outUpac_s = session1.get_bulk("ifOutUcastPkts", 0, int(number1.value)) for i in outUpac_s: temp3_s = temp3_s + int(i.value) outNUpac_s = session1.get_bulk("ifOutNUcastPkts", 0, int(number1.value)) for i in outNUpac_s: temp4_s = temp4_s + int(i.value) inUpac_r = session2.get_bulk("ifInUcastPkts", 0, int(number2.value)) for i in inUpac_r: temp1_r = temp1_r + int(i.value) inNUpac_r = session2.get_bulk("ifInNUcastPkts", 0, int(number2.value)) for i in inNUpac_r: temp2_r = temp2_r + int(i.value) outUpac_r = session2.get_bulk("ifOutUcastPkts", 0, int(number2.value)) for i in outUpac_r: temp3_r = temp3_r + int(i.value) outNUpac_r = session2.get_bulk("ifOutNUcastPkts", 0, int(number2.value)) for i in outNUpac_r: temp4_r = temp4_r + int(i.value) in_tot_s = temp1_s + temp2_s out_tot_s = temp3_s + temp4_s in_tot_r = temp1_r + temp2_r out_tot_r = temp3_r + temp4_r rrdtool.update('/var/www/html/mrtg/switch.rrd', 'N:%d:%d' % (in_tot_s, out_tot_s)) rrdtool.update('/var/www/html/mrtg/router.rrd', 'N:%d:%d' % (in_tot_r, out_tot_r)) FILE1 = '/var/www/html/mrtg/switch.rrd' FILE2 = '/var/www/html/mrtg/router.rrd' fd, path = tempfile.mkstemp('.png') info = rrdtool.info(FILE1) st = int(info['last_update'] - 340) en = int(info['last_update']) rrdtool.graph("/var/www/html/mrtg/switch.png", "-s %d" % st, "-e %d" % en, "--x-grid=MINUTE:1:HOUR:1:MINUTE:1:0:%X", '--watermark=Time', "-w 600", "-h 350", "--vertical-label=Packet Rate", "-t Switch traffic: Past 5 minutes", "DEF:s_in=/var/www/html/mrtg/switch.rrd:in:AVERAGE", "DEF:s_out=/var/www/html/mrtg/switch.rrd:out:AVERAGE", "LINE1:s_in#0000FF:Packets In\r", "LINE2:s_out#00FF00:Packets Out\r") rrdtool.graph("/var/www/html/mrtg/router.png", "-s %d" % st, "-e %d" % en, "--x-grid=MINUTE:1:HOUR:1:MINUTE:1:0:%X", '--watermark=Time', "-w 600", "-h 350", "--vertical-label=Packet Rate", "-t Router traffic: Past 5 minutes", "DEF:r_in=/var/www/html/mrtg/router.rrd:in:AVERAGE", "DEF:r_out=/var/www/html/mrtg/router.rrd:out:AVERAGE", "LINE1:r_in#0000FF:Packets In\r", "LINE2:r_out#00FF00:Packets Out\r")
valueIN1 = {} valueIN2 = {} valueOUT1 = {} valueOUT2 = {} IN_BitsPerSec = {} OUT_BitsPerSec = {} Sum_IN = 0 Sum_OUT = 0 MAX_IN = int(input('Insert max UPLOAD band: ')) MAX_OUT = int(input('Insert max DOWNLOAD band: ')) print('Numero de interfaces:' + ifNumber.value) while ((Sum_IN < MAX_IN) or (Sum_OUT < MAX_OUT)): Bulk = session.get_bulk(['ifInOctets', 'ifOutOctets'], 0, numberInterfaces) time.sleep(5) Bulk2 = session.get_bulk(['ifInOctets', 'ifOutOctets'], 0, numberInterfaces) for i in range(numberInterfaces): ifInOctets1 = Bulk[i] ifOutOctets1 = Bulk[i + 1] ifInOctets2 = Bulk2[i] ifOutOctets2 = Bulk2[i + 1] valueIN1[i] = int(ifInOctets1.value) valueOUT1[i] = int(ifOutOctets1.value) valueIN2[i] = int(ifInOctets2.value) valueOUT2[i] = int(ifOutOctets2.value)
olt = OLT_Summary() gpon_port_initial_index = 4194312190 oids = [] oids.append('IF-MIB::ifDescr.' + str(gpon_port_initial_index)) oids.append('IF-MIB::ifAlias.' + str(gpon_port_initial_index)) oids.append('.1.3.6.1.4.1.2011.6.128.1.1.2.43.1.3.' + str(gpon_port_initial_index)) #ONT Serial Number oids.append('.1.3.6.1.4.1.2011.6.128.1.1.2.45.1.4.' + str(gpon_port_initial_index)) #ONT Type oids.append('.1.3.6.1.4.1.2011.6.128.1.1.2.46.1.15.' + str(gpon_port_initial_index)) #ONT Status ont_sn_stats = session.get_bulk(oids, non_repeaters=0, max_repetitions=snmp_max_repetitions) for item in ont_sn_stats: if item.oid == '.1.3.6.1.2.1.2.2.1.2': #ifDescr if "GPON_UNI" in item.value: olt.gpon_ports[item.oid_index] = GPON_Port(str(item.value)) olt.gpon_ports[item.oid_index].ifDescr = str(item.value) elif item.oid == '.1.3.6.1.2.1.31.1.1.1.18': #ifAlias if item.oid_index in olt.gpon_ports: olt.gpon_ports[item.oid_index].setIfAlias(str(item.value)) elif '.1.3.6.1.4.1.2011.6.128.1.1.2.43.1.3.' in item.oid: #ONT Serial Number oid_index = item.oid.replace('.1.3.6.1.4.1.2011.6.128.1.1.2.43.1.3.', '') if oid_index in olt.gpon_ports: ont_id = int(item.oid_index)
uptime = session.get('sysUpTimeInstance') print("Uptime = " + uptime.value + "\n") # NOME name = session.get('sysName.0') print("Name = " + name.value + "\n") # NUM INTERFACES interfaces = session.get('ifNumber.0') print("Interfaces = " + interfaces.value + "\n") numInterfaces = int(interfaces.value) # MACs print("\nMACs:") endMAC = [] countBulk = session.get_bulk(['ifPhysAddress'], 0, numInterfaces) for i in range(numInterfaces): endMAC.append(countBulk[i]) print(endMAC[i].value) # IPs print("\nIPs:") endIP = [] countBulk = session.get_bulk(['ipAdEntAddr'], 0, numInterfaces) for i in range(numInterfaces): endIP.append(countBulk[i]) print(endIP[i].value) # BYTES ENVIADOS print("\nBytes Enviados:") bytesOut = []
class Device(): def __init__(self, IPaddress, Port, Community, Version, Timeout): self.dev = Session(hostname=IPaddress, remote_port=Port, community=Community, version=Version, timeout=Timeout) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ READ METHODS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #Method to numeric variable from regular OID def read_num(self, VarNameList, OIDList, MultiplierList): # Arguments: # VarNameList : list of variable name # OIDList : list of variable OID address # MultiplierList : list of multiplier # Return : dictionary of variable name and its value self.values = [] self.operation = math.ceil(len(OIDList) / dataPerAccess) i = 0 for opr in range(self.operation): try: data = self.dev.get(OIDList[i:i + dataPerAccess]) except: data = self.dev.get(OIDList[i:]) for item in data: self.values.append(int(item.value)) i += dataPerAccess for i in range(0, len(self.values)): self.values[i] = round(self.values[i] * MultiplierList[i], 3) self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to string variable from regular OID def read_string(self, VarNameList, OIDList): # Arguments: # VarNameList : list of variable name # OIDList : list of variable OID address # Return : dictionary of variable name and its value self.values = [] self.operation = math.ceil(len(OIDList) / dataPerAccess) i = 0 for opr in range(self.operation): try: data = self.dev.get(OIDList[i:i + dataPerAccess]) except: data = self.dev.get(OIDList[i:]) for item in data: self.values.append(str(item.value)) i += dataPerAccess self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to string variable from Table OID def read_num_tab(self, VarNameList, OIDList, rowList, MultiplierList): # Arguments: # VarNameList : list of variable name # OIDList : list of variable OID address # rowList : list of total row that we want to get from table column (max repetition in getBulk operation) # MultiplierList : list of multiplier # Return : dictionary of variable name and its value self.values = [] self.Result = {} i = 0 for oid in OIDList: data = self.dev.get_bulk(oid, max_repetitions=rowList[i]) j = 1 for item in data: self.Result[VarNameList[i] + "_%d" % j] = round( int(item.value) * MultiplierList[i], 3) j += 1 i += 1 return self.Result #Method to string variable from Table OID def read_string_tab(self, VarNameList, OIDList, rowList): # Arguments: # VarNameList : list of variable name # OIDList : list of variable OID address # rowList : list of total row that we want to get from table column (max repetition in getBulk operation) # Return : dictionary of variable name and its value self.values = [] self.Result = {} i = 0 for oid in OIDList: data = self.dev.get_bulk(oid, max_repetitions=rowList[i]) j = 1 for item in data: self.Result[VarNameList[i] + "_%d" % j] = str(item.value) j += 1 i += 1 return self.Result #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ WRITE METHODS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# # Method to write a value in single OID def write(self, OID, value, snmp_type=None): # Arguments: # OID : object identifier of a variable # value : value that you want to write in the OID # snmp_type : data type in object # if snmp_type == None: self.dev.set(registerAddress, value) else: self.dev.set(registerAddress, value, snmp_type) # Method to write values in multiple OIDs def write_multiple(self, OIDList, valueList, snmp_type=None): # Arguments: # OIDList : list of object identifier # valueList : list of value if snmp_type == None: oid_val = list(zip(OIDList, valueList)) self.dev.set_multiple(oid_val) else: oid_val = list(zip(OIDList, valueList, snmp_type)) self.dev.set_multiple(oid_val)
from easysnmp import Session import time session = Session(hostname="192.168.0.105", version=3, security_level="auth_with_privacy", security_username="******", auth_protocol="MD5", auth_password="******", privacy_protocol="DES", privacy_password="******") while 1: blockedSite = 0 openTcpConnections = int(session.get('tcpCurrEstab.0').value) + 2 tcpConnections = session.get_bulk(['tcpConnState'], 0, openTcpConnections) #print tcpConnections[0] for i in range(openTcpConnections): result = tcpConnections[i].oid_index.find('143.54.2.20') if result != -1: blockedSite = 1 #print tcpConnections inputErrors = session.get('ifInErrors.1') inputUnicastPackets = session.get('ifInUcastPkts.1') inputNoUnicastPackets = session.get('ifInNUcastPkts.1') inputErrorPercentage = int(inputErrors.value) / ( int(inputUnicastPackets.value) + int(inputNoUnicastPackets.value))
session = Session(hostname='localhost', community='public', version=2, use_sprint_value=True) name = session.get('sysName.0') upTime = session.get('hrSystemUptime.0') numberProcess = session.get('hrSystemProcesses.0') ifNumber = session.get('ifNumber.0') numberInterfaces = int(ifNumber.value) vector_IP = {} vector_MAC = {} print('Nome do host:' + name.value) print('Uptime:' + upTime.value) print('Numero de processos:' + numberProcess.value) print('Numero de interfaces:' + ifNumber.value) Bulk1 = session.get_bulk('ipAdEntAddr', 0, numberInterfaces) Bulk2 = session.get_bulk('ifPhysAddress', 0, numberInterfaces) for i in range(numberInterfaces): address_IP = Bulk1[i] vector_IP[i] = address_IP.value address_MAC = Bulk2[i] vector_MAC[i] = address_MAC.value print "Interface", i print "IP:", vector_IP[i] print "MAC:", vector_MAC[i]