def turn_off_psu(self, psu_id): """ @summary: Use SNMP to turn off power to PSU of DUT specified by psu_id DUT hostname must be configured in PDU port name/description. But it is hard to specify which PDU port is connected to the first PSU of DUT and which port is connected to the second PSU. Because of this, currently we just find out which PDU ports are connected to PSUs of which DUT. We cannot find out the exact mapping between PDU ports and PSUs of DUT. To overcome this limitation, the trick is to convert the specified psu_id to integer, then calculate the mode upon the number of PSUs on DUT. The calculated mode is used as an index to get PDU ports ID stored in self.pdu_ports. But still, we cannot gurante that psu_id 0 is first PSU of DUT, and so on. @param psu_id: ID of the PSU on SONiC DUT @return: Return true if successfully execute the command for turning off power. Otherwise return False. """ port_oid = self.pPORT_CONTROL_BASE_OID + self.pdu_ports[ rfc1902.Integer(psu_id)] errorIndication, errorStatus, _, _ = \ cmdgen.CommandGenerator().setCmd( cmdgen.CommunityData(self.snmp_rwcommunity), cmdgen.UdpTransportTarget((self.controller, 161)), (port_oid, rfc1902.Integer(self.CONTROL_OFF)), ) if errorIndication or errorStatus != 0: logging.debug("Failed to turn on PSU %s, exception: %s" % (str(psu_id), str(errorStatus))) return False return True
def testPacking(self): """Test pack() function""" self.assertEqual(basictypes.build("SNIMPY-MIB", "snimpyString", "Hello world").pack(), rfc1902.OctetString("Hello world")) self.assertEqual(basictypes.build("SNIMPY-MIB", "snimpyInteger", 18).pack(), rfc1902.Integer(18)) self.assertEqual(basictypes.build("SNIMPY-MIB", "snimpyInteger", 1804).pack(), rfc1902.Integer(1804)) self.assertEqual(basictypes.build("SNIMPY-MIB", "snimpyEnum", "testing").pack(), rfc1902.Integer(3)) self.assertEqual(basictypes.build("SNIMPY-MIB", "snimpyIpAddress", "10.11.12.13").pack(), rfc1902.IpAddress("10.11.12.13")) self.assertEqual(basictypes.build("SNIMPY-MIB", "snimpyObjectId", (1, 2, 3, 4)).pack(), rfc1902.univ.ObjectIdentifier((1, 2, 3, 4))) self.assertEqual(basictypes.build("SNIMPY-MIB", "snimpyTimeticks", timedelta(3, 2)).pack(), rfc1902.TimeTicks(3 * 3600 * 24 * 100 + 2 * 100)) self.assertEqual(basictypes.build("SNIMPY-MIB", "snimpyBits", [1, 7]).pack(), rfc1902.Bits(b"\x41"))
def add_ipv6_address(self, address): """ Add the given IPv6 address to the VLAN. `address` should be of type ipaddress.IPv6Interface. """ # TODO: Convert a HP-ICF-IPCONFIG with this OID to pysnmp format hpicfIpv6InterfaceCfgEnableStatus = (1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 10, 3, 2, 1, 1, 6) hpicfIpv6InterfaceManual = (1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 10, 3, 2, 1, 1, 2) ipv6_address_tuple = struct.unpack("16B", address.ip.packed) self.switch.snmp_set( # Set enabled and configure a link-local address (hpicfIpv6InterfaceCfgEnableStatus + (self.ifindex, ), rfc1902.Integer(1)), # Enable manual address configuration (hpicfIpv6InterfaceManual + (self.ifindex, ), rfc1902.Integer(1)), (("ipv6InterfaceEnableStatus", self.ifindex), rfc1902.Integer(1)), (("hpicfIpAddressPrefixLength", self.ifindex, 2, 16) + ipv6_address_tuple, rfc1902.Gauge32(address.prefixlen)), # hpicfIpAddressType unicast (("hpicfIpAddressType", self.ifindex, 2, 16) + ipv6_address_tuple, rfc1902.Integer(1)), # hpicfIpAddressRowStatus createAndGo 4 (("hpicfIpAddressRowStatus", self.ifindex, 2, 16) + ipv6_address_tuple, rfc1902.Integer(4)))
def pack(self): if self._value >= (1 << 64): raise OverflowError("too large to be packed") if self._value >= (1 << 32): return rfc1902.Counter64(self._value) if self._value >= 0: return rfc1902.Integer(self._value) if self._value >= -(1 << 31): return rfc1902.Integer(self._value) raise OverflowError("too small to be packed")
def main(): # Configure logging for path in ('logging.yml', 'logging.default.yml'): if not os.path.isfile(path): continue with open(path, 'rt') as file: config = yaml.load(file) logging.config.dictConfig(config) # Parse arguments par = argparse.ArgumentParser( description='Export network device configuration via SNMP') par.add_argument('-V', '--version', action='version', version=__version__) par.add_argument('-c', '--community', default='public') par.add_argument('--debug-local-port', dest='local_port', default=69, type=int) par.add_argument('--debug-remote-port', dest='remote_port', default=161, type=int) par.add_argument('--debug-filename', dest='filename', default=None, type=int) par.add_argument('--debug-no-trigger', dest='no_trigger', action="store_true", default=False) par.add_argument('local_addr') par.add_argument('remote_addr') args = par.parse_args() # Determine random filename if args.filename is None: charset = (string.ascii_lowercase + string.digits)[:32] assert 256 % len(charset) == 0 # even distribution filename = "".join(charset[ord(x) % len(charset)] for x in os.urandom(16)) else: filename = args.filename # Start server server = TftpServer((args.local_addr, args.local_port)) server.start() file_obj = server.receive(filename) # Tell switch to start upload if not args.no_trigger: i = random.randint(100000, 999999) snmp = pysnmp.CommandGenerator() community = pysnmp.CommunityData(args.community) target = pysnmp.UdpTransportTarget((args.remote_addr, args.remote_port)) errIndication, errStatus, errIndex, varBinds = snmp.setCmd(community, target, ("1.3.6.1.4.1.9.9.96.1.1.1.1.2.%i" % i, pysnmp_types.Integer(1)), ("1.3.6.1.4.1.9.9.96.1.1.1.1.3.%i" % i, pysnmp_types.Integer(4)), ("1.3.6.1.4.1.9.9.96.1.1.1.1.4.%i" % i, pysnmp_types.Integer(1)), ("1.3.6.1.4.1.9.9.96.1.1.1.1.5.%i" % i, pysnmp_types.IpAddress(args.local_addr)), ("1.3.6.1.4.1.9.9.96.1.1.1.1.6.%i" % i, pysnmp_types.OctetString(filename))) errIndication, errStatus, errIndex, varBinds = snmp.setCmd(community, target, ("1.3.6.1.4.1.9.9.96.1.1.1.1.14.%i" % i, pysnmp_types.Integer(1))) else: print("filename: %s" % filename) # Wait for upload to finish print file_obj.read()
def send_trap(self): """ Send a SNMP trap with id `trapid` to the IP address `manager` """ oid = self.options.eoid # cascade enterprise Object ID trapid = self.options.trapid # base string for trap indicators community = self.options.community manager_ip = self.options.manager_ip severity = self.options.severity description = self.trap_description url = self.options.trap_url alert_level = self.options.alert_level now = timeutils.datetime_to_seconds(datetime.datetime.now()) trapname = '.'.join([oid, trapid]) ntf = ntforg.NotificationOriginator() err = ntf.sendNotification(ntforg.CommunityData(community), ntforg.UdpTransportTarget((manager_ip, 162)), 'trap', trapname, ('1.3.6.1.2.1.1.3.0', rfc1902.Integer(0)), # Uptime ('1.3.6.1.4.1.7054.71.2.1.0', rfc1902.Integer(severity)), # Severity ('1.3.6.1.4.1.7054.71.2.3.0', rfc1902.OctetString(description)), ('1.3.6.1.4.1.7054.71.2.4.0', rfc1902.Integer(0)), # Event ID ('1.3.6.1.4.1.7054.71.2.5.0', rfc1902.OctetString(url)), ('1.3.6.1.4.1.7054.71.2.7.0', rfc1902.Integer(alert_level)), # Alert Level ('1.3.6.1.4.1.7054.71.2.8.0', rfc1902.Integer(now)), # Start Time ('1.3.6.1.4.1.7054.71.2.16.0', rfc1902.Integer(0)), # Source Count ('1.3.6.1.4.1.7054.71.2.18.0', rfc1902.Integer(0)), # Destination Count ('1.3.6.1.4.1.7054.71.2.20.0', rfc1902.Integer(0)), # Protocol Count ('1.3.6.1.4.1.7054.71.2.22.0', rfc1902.Integer(0)), # Port Count )
def setup_snmp_trap(self, alert): oid = self.eoid # cascade enterprise Object ID trapid = self.trapid # base string for trap indicators self.trapname = '.'.join([oid, trapid]) severity = self.severity description = alert.message or self.default_description alert_level = AlertLevels.get_integer(self.level) now = timeutils.datetime_to_seconds(alert.timestamp) self.binds = ( ('1.3.6.1.2.1.1.3.0', rfc1902.Integer(0)), # Uptime ('1.3.6.1.4.1.7054.71.2.1.0', rfc1902.Integer(severity)), # Severity ('1.3.6.1.4.1.7054.71.2.3.0', rfc1902.OctetString(description)), ('1.3.6.1.4.1.7054.71.2.4.0', rfc1902.Integer(0)), # Event ID ('1.3.6.1.4.1.7054.71.2.5.0', rfc1902.OctetString(self.trap_url)), ('1.3.6.1.4.1.7054.71.2.7.0', rfc1902.Integer(alert_level)), # Alert Level ('1.3.6.1.4.1.7054.71.2.8.0', rfc1902.Integer(now)), # Start Time ('1.3.6.1.4.1.7054.71.2.16.0', rfc1902.Integer(0)), # Source Count ('1.3.6.1.4.1.7054.71.2.18.0', rfc1902.Integer(0)), # Destination Count ('1.3.6.1.4.1.7054.71.2.20.0', rfc1902.Integer(0)), # Protocol Count ('1.3.6.1.4.1.7054.71.2.22.0', rfc1902.Integer(0)), # Port Count )
def deleteVLAN(self, vlanName): """\brief Deletes the vlan indicated by the given vlan name. This function will delete the vlan regardless of whether it contains ports or not and returns the following codes: -1: if the vlan does not exist on the switch -2: if the operation to delete the vlan's 802.1Q failed -3: if the snmpset command to delete the vlan fails 0: if successful \param vlanName (\c string) The name of the vlan to delete \return (\c int) 0 if successful, negative otherwise """ vi = self.getFullVLANInfo(vlanName) if len(vi) == 1: vlan = vi[0] else: return -1 if (vlan.getInternalID() == -1): return -1 # delete ports res = self.deletePorts(vlanName, vlan.getPortsOnSwitch(self.getSwitchName())) if res != 0: print "problem deleting ports in vlan" return -3 # First delete any 802.1Q interfaces associated with this vlan if vlan.getTaggedID() != None: self.snmp.set( OID.ifStackStatus + (vlan.getInternalID(), vlan.getTaggedID()), rfc1902.Integer(6)) if self.snmp.getErrorStatus(): print "unable to delete tagged vlan entry interface" print self.snmp print -3 self.snmp.set( OID.extremeVlanTaggedRowStatus + (vlan.getTaggedID(), ), rfc1902.Integer32(6)) if self.snmp.getErrorStatus(): print "unable to delete tagged interface" print self.snmp print -3 # At this point we have a valid vlan, delete it (this command deletes the # vlan regardless of whether it contains ports or not self.snmp.set( OID.extremeVlanStaticRowStatus + (vlan.getInternalID(), ), rfc1902.Integer(6)) if self.snmp.getErrorStatus(): print "Error with deleting vlan : " #+str(mylist[int(self.snmp.getErrorIndex())-1]) print self.snmp return -3 return 0
def change_channel(ip, polarity, frequency, symbol_rate, service_num): retVal = True #change polarity errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator( ).setCmd(cmdgen.CommunityData('python-agent', 'private'), cmdgen.UdpTransportTarget((ip, 161)), ((1, 3, 6, 1, 4, 1, 1773, 1, 3, 208, 2, 2, 1, 0), rfc1902.Integer(polarity))) if errorIndication: retVal = False logger.error(errorIndication) time.sleep(.5) #frequency and symbol rate must be changed on the input we are using input = polarity + 1 #change frequency errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator( ).setCmd(cmdgen.CommunityData('python-agent', 'private'), cmdgen.UdpTransportTarget((ip, 161)), ((1, 3, 6, 1, 4, 1, 1773, 1, 3, 208, 2, 2, 15, 1, 3, input), rfc1902.Integer(frequency))) if errorIndication: retVal = False logger.error(errorIndication) time.sleep(.5) #change symbol rate errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator( ).setCmd(cmdgen.CommunityData('python-agent', 'private'), cmdgen.UdpTransportTarget((ip, 161)), ((1, 3, 6, 1, 4, 1, 1773, 1, 3, 208, 2, 2, 15, 1, 4, input), rfc1902.Integer(symbol_rate))) if errorIndication: retVal = False logger.error(errorIndication) time.sleep(.5) #change mpeg service number errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator( ).setCmd(cmdgen.CommunityData('python-agent', 'private'), cmdgen.UdpTransportTarget((ip, 161)), ((1, 3, 6, 1, 4, 1, 1773, 1, 3, 208, 4, 1, 2, 0), rfc1902.Integer(service_num))) if errorIndication: retVal = False logger.error(errorIndication) return retVal
def writeMemory(host): row = random.randrange(1, 10) errorIndication, errorStatus, errorIndex, varBinds = setCMD( host, Cisco_ccCopySourceFileType + (row, ), rfc1902.Integer(4)) source_result = { 'errorIndication': errorIndication, 'errorStatus': errorStatus, 'errorIndex': errorIndex, 'value': varBinds } errorIndication, errorStatus, errorIndex, varBinds = setCMD( host, Cisco_ccCopyDestFileType + (row, ), rfc1902.Integer(3)) dest_result = { 'errorIndication': errorIndication, 'errorStatus': errorStatus, 'errorIndex': errorIndex, 'value': varBinds } errorIndication, errorStatus, errorIndex, varBinds = setCMD( host, Cisco_ccCopyEntryRowStatus + (row, ), rfc1902.Integer(1)) dest_result = { 'errorIndication': errorIndication, 'errorStatus': errorStatus, 'errorIndex': errorIndex, 'value': varBinds } ok = False while not ok: errorIndication, errorStatus, errorIndex, varBinds = getCMD( host, Cisco_ccCopyState + (row, )) state_result = { 'errorIndication': errorIndication, 'errorStatus': errorStatus, 'errorIndex': errorIndex, 'value': varBinds } if not state_result['value']: state_result['value'] = 0 return state_result else: tmp = state_result['value'] state_result['value'] = tmp[0][1] if state_result['value'] == 3 or state_result['value'] == 4: ok = True return state_result
def _switchport_mode_trunk_init(self, nos_host, port_num): """Enable a port as VLAN trunk mode.""" LOG.debug(_('_switchport_mode_trunk_init %s %d'), nos_host, port_num) oid_table = self._get_oid_table(nos_host) """Change switchport to trunk mode, and set PVID = 1""" varBinds = [] TAGGED = 2 snmp_oid = oid_enterprise + oid_table['agPortNewCfgVlanTag'] + (port_num,) value = rfc1902.Integer(TAGGED) varBinds += (snmp_oid, value), snmp_oid = oid_enterprise + oid_table['agPortNewCfgPVID'] + (port_num,) value = rfc1902.Integer32(1) varBinds += (snmp_oid, value), self._set(nos_host, varBinds) """Remove all other VLAN except 1 for the first time config this port""" max_vlan_id = 4094 vlans = range(2, max_vlan_id+1) varBinds = [] for vid in vlans: snmp_oid = oid_enterprise + oid_table['vlanNewCfgRemovePort'] + (vid,) value = rfc1902.Gauge32(port_num) varBinds += (snmp_oid, value), if vid%20 == 0: self._set(nos_host, varBinds) varBinds = [] self._set(nos_host, varBinds)
def snmpv2_set(ip, community, oid, value, port=161): cmdGen = cmdgen.CommandGenerator() # print(dir(rfc1902)) # 类型 ['ApplicationSyntax', 'Bits', 'Counter32', 'Counter64', 'Gauge32', 'Integer', 'Integer32', 'IpAddress', 'ObjectIdentifier', 'ObjectName', 'ObjectSyntax', 'OctetString', 'Opaque', 'SimpleSyntax', 'TimeTicks', 'Unsigned32', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'constraint', 'error', 'namedtype', 'namedval', 'rfc1155', 'tag', 'univ', 'version_info'] # 需要提前通过OIDVIEW查询类型 # 通过不同的类型写入数据 if isinstance(value, str): set_value = rfc1902.OctetString(value) elif isinstance(value, int): set_value = rfc1902.Integer(value) errorIndication, errorStatus, errorindex, varBinds = cmdGen.setCmd( cmdgen.CommunityData(community), # 写入Community cmdgen.UdpTransportTarget((ip, port)), # IP地址和端口号 (oid, set_value) # OID和写入的内容,需要进行编码! ) # 错误处理 if errorIndication: print("写入错误!!!") print(errorIndication) elif errorStatus: print("写入错误!!!") print('%s at %s' % (errorStatus.prettyPrint(), errorindex and varBinds[int(errorindex) - 1][0] or '?')) else: print("写入成功!!!") # 打印回显示结果 for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # 打印修改的结果
def do_run(): snmpEkinops.read_config() snmputils.set_logger_format(name=snmpEkinops.name()) cmd_gen = snmputils.get_cmd_gen() while True: try: for interface in snmpEkinops.interfaces(): interfaceId = interface.split(':')[0] cardType = interface.split(':')[1] ipAddr = socket.gethostbyname(snmpEkinops.destination()) # Get the card number oid_args = [mgnt2Position + "." + interfaceId] logging.debug('get card number, oid_args=%s', oid_args) var_binds = snmputils.query_ekinops_card( cmd_gen, snmpEkinops.security_object(), snmpEkinops.transport(), oid_args) card_number = var_binds[0][1].prettyPrint() # Set card to read from oid_args = [ str(mgnt2GigmSelectedBoard), rfc1902.Integer(card_number) ] logging.debug('set card number, oid_args=%s', oid_args) snmp_result = cmd_gen.setCmd(snmpEkinops.security_object(), snmpEkinops.transport(), oid_args) # Create array of oids to read oid_args = [ interface_mibs[e] + ".0" for e in managed_oids[cardType] ] logging.debug('queryOids, oid_args=%s', oid_args) var_binds = snmputils.query_oids(cmd_gen, snmpEkinops.security_object(), snmpEkinops.transport(), oid_args) logging.debug('var_binds=%s', var_binds) interface_attrs = {} interface_attrs['card'] = card_number interface_attrs['interfaceIdx'] = interfaceId interface_attrs['cardType'] = cardType interface_attrs['ipAddr'] = ipAddr handle_output(var_binds, snmpEkinops.destination(), interface_attrs) except SnmpException as ex: logging.error('error=%s msg=%s interfaces=%s', splunk_escape(ex.error_type), splunk_escape(ex.msg), splunk_escape(','.join(snmpEkinops.interfaces()))) except PySnmpError as ex: logging.error('msg=%s', splunk_escape(ex.message)) except Exception: logging.exception('msg="Exception in main loop"') time.sleep(float(snmpEkinops.snmpinterval()))
def testpage(self, pagetype=DEFAULT_TESTPAGE): try: pagetype = rfc1902.Integer(TESTPAGE_MAP[pagetype]) except KeyError: raise ValueError('Invalid testpage type: %s' % pagetype) oid = HP_LASERJET_MIB_OID + '.4.2.1.1.5.2.0' return self.client.set(oid, pagetype)
def reset(self, resettype=DEFAULT_RESET_TYPE): try: resettype = rfc1902.Integer(RESET_TYPE_MAP[resettype]) except KeyError: raise ValueError('Invalid reset type: %s' % resettype) oid = PRINTER_MIB_OID + '.5.1.1.3.1' return self.client.set(oid, resettype)
def powerOff(self): thisoid = eval(str(self.oid) + str(self.oid_status) + "," + str(self.port)) __errorIndication, __errorStatus, __errorIndex, __varBinds = cmdgen.CommandGenerator().setCmd( \ cmdgen.CommunityData('my-agent', self.user, 1), \ cmdgen.UdpTransportTarget((self.pdu_name, 161)), \ (thisoid, rfc1902.Integer('0'))) return self.getPowerStatus()
def set_by_oid(self, oid, value, community='private', snmpv3cred=('authkey1', 'privkey1')): """Return the results of an SNMP SET.""" # TODO fix the test-agent and test-user usage here if self.snmpver == 1: authdata = cmdgen.CommunityData('test-agent', community, 0) elif self.snmpver == 2: authdata = cmdgen.CommunityData('test-agent', community) elif self.snmpver == 3: authdata = cmdgen.UsmUserData( 'test-user', snmpv3cred[0], snmpv3cred[1] ) if isinstance(value, int): errorindication, errorstatus, errorindex, varbinds = \ cmdgen.CommandGenerator().setCmd( authdata, cmdgen.UdpTransportTarget( (self.host, self.snmpport)), (oid, rfc1902.Integer(value)) ) if errorindication: return str(errorindication) else: if errorstatus: return varbinds[0][1].prettyPrint() else: return varbinds[0][1].prettyPrint()
def turn_off_outlet(self, outlet): """ @summary: Use SNMP to turn off power to PDU outlet of DUT specified by outlet DUT hostname must be configured in PDU port name/description. But it is hard to specify which PDU port is connected to the first PSU of DUT and which port is connected to the second PSU. Because of this, currently we just find out which PDU outlets are connected to PSUs of which DUT. We cannot find out the exact mapping between PDU outlets and PSUs of DUT. @param outlet: ID of the outlet on PDU @return: Return true if successfully execute the command for turning off power. Otherwise return False. """ if not self.pduType: logging.error('Unable to turn off: PDU type is unknown: pdu_ip {}'.format(self.controller)) return False port_oid = '.' + self.PORT_CONTROL_BASE_OID + outlet errorIndication, errorStatus, _, _ = \ cmdgen.CommandGenerator().setCmd( cmdgen.CommunityData(self.snmp_rwcommunity), cmdgen.UdpTransportTarget((self.controller, 161)), (port_oid, rfc1902.Integer(self.CONTROL_OFF)) ) if errorIndication or errorStatus != 0: logging.debug("Failed to turn on outlet %s, exception: %s" % (str(outlet), str(errorStatus))) return False return True
def __coerce_value(initial_value, new_value): """Coerce the new_value to the same type as the initial_value. :param initial_value: initial value from the device :param new_value: new value to set, coerced into the right type :return: new value, coerced into the right type """ # pylint: disable=redefined-variable-type # In order to return the right type the return value has to be # redefined. # Types from RFC-1902 if isinstance(initial_value, rfc1902.Counter32): set_value = rfc1902.Counter32(str(new_value)) elif isinstance(initial_value, rfc1902.Counter64): set_value = rfc1902.Counter64(str(new_value)) elif isinstance(initial_value, rfc1902.Gauge32): set_value = rfc1902.Gauge32(str(new_value)) elif isinstance(initial_value, rfc1902.Integer): set_value = rfc1902.Integer(str(new_value)) elif isinstance(initial_value, rfc1902.Integer32): set_value = rfc1902.Integer32(str(new_value)) elif isinstance(initial_value, rfc1902.IpAddress): set_value = rfc1902.IpAddress(str(new_value)) elif isinstance(initial_value, rfc1902.OctetString): set_value = rfc1902.OctetString(str(new_value)) elif isinstance(initial_value, rfc1902.TimeTicks): set_value = rfc1902.TimeTicks(str(new_value)) elif isinstance(initial_value, rfc1902.Unsigned32): set_value = rfc1902.Unsigned32(str(new_value)) else: raise RuntimeError("Unknown type %s" % type(initial_value)) return set_value
def snmp_send(community, ip, port, oid): cmdGen = cmdgen.CommandGenerator() cmdGen.setCmd( cmdgen.CommunityData(community, mpModel=1), cmdgen.UdpTransportTarget((ip, port)), (oid, rfc1902.Integer(-1)), )
def _set_enabled(self, value): """ Set the admin status of this port. """ # ifAdminStatus 1 means up, 2 means down self.switch.snmp_set((("ifAdminStatus", self.ifindex), rfc1902.Integer(1 if value else 2)))
def disablePort(self, portNumber): """\brief Disables a port. Returns 0 upon success, -1 otherwise \param portNumber (\c string) The port to disable \return (\c int) 0 if succesful, -1 otherwise """ internalID = int(self.getPortInternalID(portNumber)) self.snmp.set(OID.ifAdminStatus+(internalID,),rfc1902.Integer(2)) return self.snmp.getErrorStatus()
class DES_Base(BaseProfile): VAL_create = rfc1902.Integer(2) VAL_destroy = rfc1902.Integer(3) async def config_save(self): oid = '1.3.6.1.4.1.171.12.1.2.6.0' val = rfc1902.Integer(5) return await self._p.request_set(self._addr, self._port, self._w, ((oid, val), )) OID_swL2McastFilterPortInfoProfileName = '' OID_swL2McastFilterPortProfileID = '' OID_swL2McastFilterPortProfileAddOrDelState = '' async def mcast_profile_status(self, port, profile_id): res = await self._p.request_get( self._addr, self._port, self._r, ((self.OID_swL2McastFilterPortInfoProfileName.format(port=port), None), )) if res['success']: bResult, = res['result'] _, status = bResult ids = map(int, str(status).split('-')) res['result'] = profile_id in ids return res async def mcast_profile_enable(self, port, profile_id): # порядок биндов важен res = await self._p.request_set(self._addr, self._port, self._w, ( (self.OID_swL2McastFilterPortProfileAddOrDelState.format( port=port), self.VAL_create), (self.OID_swL2McastFilterPortProfileID.format(port=port), rfc1902.Integer(profile_id)), )) return res async def mcast_profile_disable(self, port, profile_id): # порядок биндов важен res = await self._p.request_set(self._addr, self._port, self._w, ( (self.OID_swL2McastFilterPortProfileAddOrDelState.format( port=port), self.VAL_destroy), (self.OID_swL2McastFilterPortProfileID.format(port=port), rfc1902.Integer(profile_id)), )) return res
async def mcast_profile_disable(self, port, profile_id): # порядок биндов важен res = await self._p.request_set(self._addr, self._port, self._w, ( (self.OID_swL2McastFilterPortProfileAddOrDelState.format( port=port), self.VAL_destroy), (self.OID_swL2McastFilterPortProfileID.format(port=port), rfc1902.Integer(profile_id)), )) return res
def _apply_config(self, nos_host): APPLY = 2 oid_table = self._get_oid_table(nos_host) varBinds = [] snmp_oid = oid_enterprise + oid_table['agApplyConfiguration'] value = rfc1902.Integer(APPLY) varBinds += (snmp_oid, value), self._set(nos_host, varBinds)
def status(self, results=None): """Returns an oid for retrieving the copy status or a string if a status is provided. """ if results is None: return self.base_oid + '10.' + self.row elif results[0][1]: index = int(rfc1902.Integer(results[0][1])) return self.copy_status[index]
def turn_on_outlet(self, outlet): errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().setCmd( cmdgen.CommunityData(self.community), cmdgen.UdpTransportTarget((self.host, 161)), ((1,3,6,1,4,1,318,1,1,12,3,3,1,1,4,outlet), rfc1902.Integer(1)) ) if errorIndication is not None: logging.error(f'Failed to set ON on {self.name}, outlet {outlet}:') logging.error(errorIndication)
def modifyPorts(self, vlanName, ports, addPorts): if (ports == None or len(ports) == 0): return 0 vlan = self.getFullVLANInfo(vlanName)[0] for p in ports: # internal and external port ids are the same p.setInternalID(p.getPortNumber()) if p.getTagged(): # tagged if addPorts: self.snmp.set( OID.ifStackStatus + (vlan.getTaggedID(), p.getInternalID()), rfc1902.Integer(4)) else: self.snmp.set( OID.ifStackStatus + (vlan.getTaggedID(), p.getInternalID()), rfc1902.Integer(6)) if self.snmp.getErrorStatus(): print "Error with adding/removing port to tagged vlan" print self.snmp return -1 else: # untagged if addPorts: self.snmp.set( OID.ifStackStatus + (vlan.getInternalID(), p.getInternalID()), rfc1902.Integer(4)) else: self.snmp.set( OID.ifStackStatus + (vlan.getInternalID(), p.getInternalID()), rfc1902.Integer(6)) if self.snmp.getErrorStatus(): print "Error with adding/removing port to untagged vlan" print self.snmp return -1 return 0
def Snmp(action=None, target_IP=None, community='public', oid=None, stype=None, value=None, walk_timeout=120): """ Name:Snmp Purpose: Do snmp set,get and walk function for DUT control. Input:1.action 2.target_IP 3.community 4.oid 5.stype 6.value 7.walk_timeout Output:Snmp get or walk result """ # Create command generator cmdGen = cmdgen.CommandGenerator() if action == "get": errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((target_IP, 161), timeout=1, retries=3), oid) for name, val in varBinds: if val.prettyPrint() != "": return val.prettyPrint() else: return "null" elif action == "set": for case in switch(stype): if case('i'): value = rfc1902.Integer(value) break elif case('s'): value = rfc1902.OctetString(value) break elif case('x'): value = rfc1902.OctetString(hexValue=value) break elif case('p'): value = rfc1902.IpAddress(value) elif case('u'): value = rfc1902.Unsigned32(value) break elif case(): # default value = "" cmdGen.setCmd( cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((target_IP, 161), timeout=1, retries=3), (oid, value))
def __update_oid_in_cachefile(self, oid, val): found = False try: s = shelve.open(self.__cache_file, "rw", writeback=True) for key in s.keys(): if oid == key: found = True break if found: s[key] = rfc1902.Integer(val, s[key].getTagSet(), s[key].getSubtypeSpec(), s[key].getNamedValues()) else: s[oid] = rfc1902.Integer(val) s.sync() s.close() except: logger.error("Update oid in cachefile failed.")