def group5id(): cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget((HOST, 161)), '1.3.6.1.2.1.25.5') if errorIndication: print(errorIndication) logsnmpget('FAIL: ID {0} - HOST {1} - {0}'.format( ID, HOST, errorIndication)) else: if errorStatus: print( '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?')) logsnmpget('FAIL: ID {0} - HOST {1} - {0}'.format( ID, HOST, errorStatus.prettyPrint())) else: pass return varBindTable
def __setPowerStatus(self): thisoid = eval(str(self.oid) + str(self.oid_status) + "," + str(self.port)) __errorIndication, __errorStatus, __errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \ cmdgen.CommunityData('my-agent', self.user, 0), \ cmdgen.UdpTransportTarget((self.pdu_name, 161)), thisoid) output = varBinds[0][1] print output, varBinds if output == 1: self.powerStatus = 1 powerstat = "on" if output == 0: self.powerStatus = 0 powerstat = "off" print "pwerstat", powerstat self.log.info("hardware setPowerStatus %s : %s" % (powerstat, self.nodeName)) if output: return 1 return 0
def getODU(myHost): try: #errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(cmdgen.CommunityData('test-agent', 'NSMX-RO', 1), cmdgen.UdpTransportTarget((myHost, 161)),(1,3,6,1,2,1,2,2,1,10,1),) errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator( ).getCmd(cmdgen.CommunityData('test-agent', 'public', 0), cmdgen.UdpTransportTarget( (myHost, 161)), (1, 3, 6, 1, 2, 1, 2, 2, 1, 10, 1), (1, 3, 6, 1, 2, 1, 2, 2, 1, 16, 1)) if errorIndication: data = [-1, -1] else: if errorStatus: data = [-1, -1] else: data = [] for name, val in varBinds: data.append(val.prettyPrint()) except: data = [-1, -1] return (data)
def getGPS(myHost): try: data = [] errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator( ).getCmd(cmdgen.CommunityData('test-agent', 'public', 0), cmdgen.UdpTransportTarget((myHost, 161)), (1, 3, 6, 1, 4, 1, 4458, 1000, 1, 5, 40, 11, 0), (1, 3, 6, 1, 4, 1, 4458, 1000, 1, 5, 40, 13, 0)) if errorIndication: data = [-1, -1] else: if errorStatus: data = [-1, -1] else: data = [] for name, val in varBinds: data.append(val.prettyPrint()) except: data = [-1, -1] return (data)
def set_router_name(router_name, new_name): _ip = get_ip_from_file("routers.txt", router_name) errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( cmdgen.CommunityData(community), cmdgen.UdpTransportTarget( (_ip, port)), ObjectType(ObjectIdentity(sysName), OctetString(new_name))) if errorIndication: print(errorIndication) else: if errorStatus: print('%s en %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1] or '?')) else: lista_aux = [] for val in varBinds: print(str(val))
def get_pools(self): cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData(self.community), cmdgen.UdpTransportTarget((self.host, self.port)), self.pool_stat_name) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?')) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: pool_id = str(name).replace(self.pool_stat_name, "") self.pool_oids[pool_id] = [str(val)]
def Set(self, msg): """Set the power status of a device. Arguments: msg: type control_pb2.SetRequest Returns: control_pb2.SetResponse """ if msg.type != control_pb2.FEAT_PWR: log.exception('Invalid Type: %d' % (msg.type)) log.debug('Got %d' % msg.value) errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.setCmd( cmdgen.CommunityData(SNMP_APC_USER, mpModel=0), cmdgen.UdpTransportTarget((self.device.server, SNMP_UDP_PORT)), (SNMP_APC_PORT_VAR + str(self.device.port), rfc1902.Integer(PWR_COMMANDS[msg.value])) ) response = control_pb2.GetResponse() self._CheckResponseOk(response, errorIndication, errorStatus, errorIndex, varBinds) return response
def snmp_get(oid, target, community="public"): from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((target, 161)), oid) # Check for errors and print out results if errorIndication: return (errorIndication) else: if errorStatus: return ('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1] or '?')) else: for name, val in varBinds: return (val)
def snmpgetwalk(*args): cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorindex, varBindTable = cmdGen.bulkCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('10.245.59.210', 30161)), 0, 2, args[0], args[1], ) if errorIndication: print(errorIndication) elif errorStatus: print('%sat%s' % ( errorStatus.prettyPrint(), errorindexandvarBinds[int(errorindex) - 1][0] or '?' ) ) for varBindTableRow in varBindTable: for name, val in varBindTableRow: print("WALK showing:", '%s=%s' % (name.prettyPrint(), val.prettyPrint()))
def info(self, oid, ip, commu): cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData(commu), cmdgen.UdpTransportTarget((ip, 161)), oid, ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) else: var_dict = {} for varBindTableRow in varBindTable: for name, val in varBindTableRow: var_dict[name.prettyPrint()] = str(val.prettyPrint()) return var_dict
def datafrommib(mib, community, ip): value = tuple([int(i) for i in mib.split('.')]) generator = cmdgen.CommandGenerator() comm_data = cmdgen.CommunityData('server', community, 1) # 1 means version SNMP v2c transport = cmdgen.UdpTransportTarget((ip, 161)) real_fun = getattr(generator, 'nextCmd') res = (errorIndication, errorStatus, errorIndex, varBindTable)\ = real_fun(comm_data, transport, value) if not errorIndication is None or errorStatus is True: print "Error: %s %s %s %s" % res yield None else: for varBindTableRow in varBindTable: data = varBindTableRow[0] port = data[0]._value[len(value):] octets = data[1] yield {'port': port[0], 'octets': octets}
def interface_list(x): int_name = [] int_oid = [] try: cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((x, 161)), '1.3.6.1.2.1.2.2.1.2', ) for varBindTableRow in varBindTable: #varBindTableRow is each interface and oid number for name, val in varBindTableRow: oid_raw = name.prettyPrint() oid = re.search(r'1.3.6.1.2.1.2.2.1.2.(\d{0,5})', oid_raw) oid = oid.group(1) int_oid.append(oid) int_name.append(val.prettyPrint()) return int_oid, int_name except: return None
def snmp_query(host, community, oid): errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((host, 161)), oid ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1] or '?' ) ) else: for name, val in varBinds: return(str(val))
def check_snmp_access(community, snmp_host): res = 0 cmdGen = cmdgen.CommandGenerator() errInd, errSt, errIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((snmp_host, 161)), snmp_oids['clusterName'], lookupMib=False) if errInd: print('UNKNOWN: Indication Error') res = 1 else: if errSt: print('%s at %s' % (errSt.prettyPrint(), errIndex and varBindTable[int(errIndex)] or '?')) res = 1 else: res = 0 return res
def snmp_bulkwalk(oid, wlc): errorIndication, errorStatus, errorIndex, varBindTable = cmdgen.CommandGenerator( ).bulkCmd( cmdgen.CommunityData(SNMP_RO), # IF using SNMPv3 uncomment the following lines, and comment out the above line #cmdgen.UsmUserData('v3user', 'usrename-123456789e', 'abcdefabcdefabcdef', #authProtocol=cmdgen.usmHMACSHAAuthProtocol, #privProtocol=cmdgen.usmAesCfb128Protocol), cmdgen.UdpTransportTarget((wlc, 161)), 0, 25, oid, ) # Check for errors if errorIndication: print(errorIndication) else: if int(errorStatus) != 0: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?')) # success oid_value = [] if int(errorStatus) == 0: for varBindTableRow in varBindTable: #print varBindTableRow for name, val in varBindTableRow: # the following returns only the OID's we are interested in, and nothing extra #print name #print(type(name)) namestr = str(name) #print(type(namestr)) if namestr[:len(oid)] == oid: #print "yes" oid_value.append((val.prettyPrint(), name.prettyPrint())) else: print "no" # return the list of OID & Values return oid_value
class SNMP(object): """ Represents a 'connection' to a certain SNMP host. """ def __init__(self, host, port=161, timeout=1, retries=5, community="public", version=2, username="", authproto="sha", authkey="", privproto="aes128", privkey=""): self._cmdgen = cmdgen.CommandGenerator() self.host = host self.port = port self.timeout = timeout self.retries = retries self.community = community self.version = version self.username = username self.authproto = authproto self.authkey = authkey self.privproto = privproto self.privkey = privkey def _get_snmp_security(self): if self.version == 3: authproto = AUTHPROTOCOLS.get(self.authproto, AUTHPROTOCOLS['noauth']) privproto = PRIVPROTOCOLS.get(self.privproto, PRIVPROTOCOLS['nopriv']) if len(self.authkey) == 0: authproto = None authkey = None else: authkey = self.authkey if len(self.privkey) == 0: privproto = None privkey = None else: privkey = self.privkey return cmdgen.UsmUserData(self.username, authKey=authkey, privKey=privkey, authProtocol=authproto, privProtocol=privproto) elif self.version == 1: return cmdgen.CommunityData(self.community, self.community,0)
def pwnrouter(host): res = {} oids = { # make, model, software version "MODEL": "1.3.6.1.2.1.1.1.0", # web interface credentials "WEB USERNAME": "******", "WEB PASSWORD": "******", # ssid and key "ESSID": "1.3.6.1.4.1.4413.2.2.2.1.5.4.1.14.1.3.10001", "PASSWORD": "******", } generator = cmdgen.CommandGenerator() for name in oids.keys(): errorIndication, errorStatus, errorIndex, varBinds = generator.getCmd( cmdgen.CommunityData('d2'), cmdgen.UdpTransportTarget((host, 161)), oids[name], lookupNames=True, lookupValues=True) if errorIndication or errorStatus: res[name] = '' continue value = str(varBinds[0][1]) res[name] = value if res: print '[+] %s vulnerable' % host print('%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n' % ( 'MODEL', res['MODEL'], 'WEB USERNAME', res['WEB USERNAME'], 'WEB PASSWORD', res['WEB PASSWORD'], 'ESSID', res['ESSID'], 'PASSWORD', res['PASSWORD'], )) else: print '[-] %s not vulnerable' % host
def _get_pdu_ports(self): """ @summary: Helper method for getting PDU ports connected to PSUs of DUT The PDU ports connected to DUT must have hostname of DUT configured in port name/description. This method depends on this configuration to find out the PDU ports connected to PSUs of specific DUT. """ max_lane = 5 host_matched = False cmdGen = cmdgen.CommandGenerator() snmp_auth = cmdgen.CommunityData(self.snmp_rocommunity) for lane_id in range(1, max_lane + 1): pdu_port_base = self.PORT_NAME_BASE_OID[0:-1] + str(lane_id) errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((self.controller, 161)), cmdgen.MibVariable("." + pdu_port_base, ), ) if errorIndication: logging.debug( "Failed to get ports controlling PSUs of DUT, exception: " + str(errorIndication)) else: for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if self.hostname.lower() in current_val.lower(): host_matched = True # Remove the preceding PORT_NAME_BASE_OID, remaining string is the PDU port ID self.pdu_ports.append( current_oid.replace(pdu_port_base, '')) if host_matched: self.map_host_to_lane(lane_id) break else: logging.error( "{} device is not attached to any of PDU port".format( self.hostname.lower()))
def getCmd(self, oid): errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.getCmd( cmdgen.CommunityData(self.access_string), cmdgen.UdpTransportTarget((self.ip, self.port)), oid) # Check for errors and print out results if errorIndication: print(errorIndication) return errorIndication else: if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?')) return errorStatus else: #print varBindTable for oid, value in varBindTable: #print value return value
def __init__(self, Community, IPAdd, StartInterfaceID=0, EndInterfaceID=0): cmdGen = cmdgen.CommandGenerator() self.name = [] I = 0 while StartInterfaceID <= EndInterfaceID: InterfaceID = str(StartInterfaceID) errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(Community), cmdgen.UdpTransportTarget((IPAdd, 161)), '1.3.6.1.2.1.2.2.1.2.' + InterfaceID, '1.3.6.1.2.1.2.2.1.10.' + InterfaceID, lookupNames=True, lookupValues=True) StartInterfaceID = StartInterfaceID + 1 name = str(varBinds[0]) OctInList = str(varBinds[1]) OctIn = OctInList[35:] self.name.append(name[-19:]) print(str(self.name[I]) + ' Bytes In: ' + OctIn) I = I + 1
def myOID(host, port, community, searchOID): cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(SNMP_COMMUNITY), cmdgen.UdpTransportTarget((host, port)), searchOID) # Check for errors and print out results if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1] or '?')) else: for name, val in varBinds: #print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) #print(f"{name.prettyPrint()}") #print(f"{val.prettyPrint()}") return val.prettyPrint()
def snmpv2_getnext(ip, community, oid, port=161): cmd_gen = cmdgen.CommandGenerator() error_indication, error_status, error_index, var_bind_table = cmd_gen.nextCmd( cmdgen.CommunityData(community), # 设置community cmdgen.UdpTransportTarget((ip, port)), # 设置IP地址和端口号 oid, # 设置OID ) # 错误处理 if error_indication: print(error_indication) elif error_status: print(error_status) result = [] # varBindTable是个list,元素的个数可能有好多个。它的元素也是list,这个list里的元素是ObjectType,个数只有1个。 for var_bind_table_row in var_bind_table: for item in var_bind_table_row: result.append((item.prettyPrint().split("=")[0].strip(), item.prettyPrint().split("=")[1].strip())) return result
def SNMPReq(self, MIBInit): """Send a SNMP request and return the response :param MIBInit: MIB (initializer) :type MIBInit: str :rtype: str :raise CheckHWGroupError: if a SNMP error occurs """ (errorIndication, errorStatus, errorIndex, varBinds) = cmdgen.CommandGenerator().getCmd( cmdgen.CommunityData(self.community, mpModel=0), cmdgen.UdpTransportTarget((self.host, self.port)), cmdgen.MibVariable(MIBInit), lookupNames=True, lookupValues=True) if errorIndication: raise CheckHWGroupError('SNMP error: {}'.format(errorIndication)) elif errorStatus: raise CheckHWGroupError('SNMP error: {}'.format(errorStatus)) else: return str(varBinds[0][1])
def snmpget(self, oid): ''' One liner for grabbing data from the given OID for the currently connected SNMP interface''' cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(self.community), cmdgen.UdpTransportTarget((self.host, self.port)), oid) print("GOT COMMAND") # Check for errors and print out results if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s'%( errorStatus.prettyPrint(),\ errorIndex and varBinds[int(errorIndex)-1] or '?')) else: for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) return val
def _get_auth_strategy(host): options = urlparse.parse_qs(host.query) kwargs = {} for key in _usm_proto_mapping: opt = options.get(key, [None])[-1] value = _usm_proto_mapping[key][1].get(opt) if value: kwargs[_usm_proto_mapping[key][0]] = value priv_pass = options.get('priv_password', [None])[-1] if priv_pass: kwargs['privKey'] = priv_pass if host.password: kwargs['authKey'] = host.password if kwargs: auth_strategy = cmdgen.UsmUserData(host.username, **kwargs) else: auth_strategy = cmdgen.CommunityData(host.username or 'public') return auth_strategy
def checkloopback45(ip,interface): loopbackpresent=False cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd( cmdgen.CommunityData('mytest'), cmdgen.UdpTransportTarget((ip, 161)), 0,25, '1.3.6.1.2.1.31.1.1.1.18','1.3.6.1.2.1.2.2.1.2','1.3.6.1.2.1.31.1.1.1.1' ) for varBindTableRow in varBindTable: tval="" for name, val in varBindTableRow: if (("Loopback45" in str(val)) or ("Lo45" in str(val))): tval=tval+"MIB: "+str(name)+" , Interface info: "+str(val)+"\n" loopbackpresent=True if (loopbackpresent): tval=tval+"IP address of the device: "+ip print (tval+"\n") if ("test interface created" in tval): pushconfig(ip,"Loopback45","Mgmt loopback interface")
def query_all_systems(self): if not self.databases_initialised: self.initialise_databases() self.databases_initialised = True cg = cmdgen.CommandGenerator() for system in self.systems.values(): comm_data = cmdgen.CommunityData('my-manager', system['communityro']) transport = cmdgen.UdpTransportTarget( (system['address'], system['port'])) for key, check in system['checks'].iteritems(): oid = check['oid'] errInd, errStatus, errIdx, result = cg.getCmd( comm_data, transport, oid) if not errInd and not errStatus: file_name = "%s.rrd" % key rrdtool.update( file_name, "%d:%d" % ( int(time.time(), ), float(result[0][1]), ))
def snmpwalk(args, oids=OIDS): """ perform snmpwalk command and return counters values; """ system, address = args values = {} cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.nextCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget((address, 161)), *list(OIDS.keys())) if errorIndication: print(system, errorIndication) for varBind in varBinds: for oidnumport, value in varBind: items = oidnumport.prettyPrint().split('.') counter = oids.get('.'.join(items[:10]), '?') port = items[-1] value = int(value.prettyPrint(), 16) if value: values['%s %s %s' % (system, port, counter)] = value return system, values
def get(self): from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() error_indication, error_status, error_index, data = cmdGen.getCmd( cmdgen.CommunityData(self.snmp_community), cmdgen.UdpTransportTarget((self.device_name, self.snmp_port)), cmdgen.MibVariable(self.mib_name, self.symbol_name, self.mib_index), lookupNames=True, lookupValues=True) if error_indication: self.error_indication = error_indication return self.error_indication elif error_status: self.error_status = error_status return self.error_status else: self.data = data return self.data
def get_snmp(ip, SnmpAttr, *Objnames): cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(SnmpAttr.COMMUNITY), cmdgen.UdpTransportTarget((ip, SnmpAttr.PORT), timeout=int(SnmpAttr.TIMEOUT), retries=int(SnmpAttr.RETRIES)), *Objnames, lookupMib=SnmpAttr.LookupMib, ) # Check for errors and print out results if errorIndication: raise SnmpError(errorIndication) else: if errorStatus: raise SnmpError(errorStatus, errorIndex, varBinds) else: vars = {} for val, name in varBinds: vars[val.prettyPrint()] = name.prettyPrint() return (vars)