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 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 server_address_rev1(self, arg=None): """Set server IP address when copying to/from a remote server.""" oid = self.base_oid + '16.' + self.row if arg is None: return oid else: value = rfc1902.IpAddress(arg) return (oid, value)
def convert_to_ip_address(self, value): """Converts a value to a SNMP IpAddress object. See `Set IP Address` for formats which are accepted for value. """ # Unfortunately, pysnmp does not support unicode strings if isinstance(value, basestring): value = str(value) return rfc1902.IpAddress(value)
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 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 snmpset(self,*args): '''This api is used for oid snmpset operation''' self.snmp_target = (self.host,self.snmp_port) cg = cmdgen.CommandGenerator() comm_data = cmdgen.CommunityData('my-manager', self.community_string) transport = cmdgen.UdpTransportTarget(self.snmp_target) snmpset_data = [] for i in range(len(args[0])): print("\nSNMP COMMAND : " + "snmpset -v2c -c " + self.community_string + ' ' + self.snmp_target[0] + ' ' + args[0][i][0] +' '+ args[0][i][2] +' '+args[0][i][1]+"\n") snmpset_data.append("\nSNMP COMMAND : " + "snmpset -v2c -c " + self.community_string + ' ' + self.snmp_target[0] + ' ' + args[0][i][0] +' '+ args[0][i][2] +' '+args[0][i][1]+"\n") print("<<<<<<<<OUTPUT>>>>>>>>>") snmpset_data.append("<<<<<<<<OUTPUT>>>>>>>>>") if args[0][i][2] == "s": variables = (args[0][i][0], rfc1902.OctetString(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "i": variables = (args[0][i][0], rfc1902.Integer(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "o": variables = (args[0][i][0], rfc1902.Bits(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "t": variables = (args[0][i][0], rfc1902.TimeTicks(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "u": variables = (args[0][i][0], rfc1902.Unsigned32(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "ip": variables = (args[0][i][0], rfc1902.IpAddress(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "U": variables = (args[0][i][0], rfc1902.Gauge32(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) else: pass # Check for errors and print out results if errIndication: print(errIndication) snmpset_data.append(errIndication) elif errStatus: print("REASON :" + '%s at %s' % (errStatus.prettyPrint(),errIndex and result[int(errIndex) - 1][0] or '?')) snmpset_data.append("REASON : "+ '%s at %s' % (errStatus.prettyPrint(),errIndex and result[int(errIndex) - 1][0] or '?')) else: for name, val in result: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) snmpset_data.append(name.prettyPrint() +" = "+ val.prettyPrint()) return snmpset_data
def get_type(v): ip_re = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") t = "" if isinstance(v, int): t = rfc1902.Integer(v) elif isinstance(v, basestring): if ip_re.match(v): t = rfc1902.IpAddress(v) else: t = rfc1902.OctetString(v) return t
def server_address_type(self, arg=None): """Set server IP address type to IPv4 or IPv6. Not Implemented - need to find 'InetAddressType' """ oid = self.base_oid + '15.' + self.row if arg is None: return oid else: #value = rfc1902.InetAddressType(arg) value = rfc1902.IpAddress(arg) return (oid, value)
class __WritePduGenerator(__ReadPduGenerator): _typeMap = { 'i': rfc1902.Integer(), 'u': rfc1902.Integer32(), 's': rfc1902.OctetString(), 'n': univ.Null(), 'o': univ.ObjectIdentifier(), 't': rfc1902.TimeTicks(), 'a': rfc1902.IpAddress() } def n_VarType(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['varType'] = node[0].attr def n_VarValue(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['varValue'] = node[0].attr def n_VarBind_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx mibViewCtl = ctx['mibViewController'] if ctx['varType'] == '=': modName, nodeDesc, suffix = mibViewCtl.getNodeLocation( ctx['varName']) mibNode, = mibViewCtl.mibBuilder.importSymbols(modName, nodeDesc) if hasattr(mibNode, 'syntax'): MibTableColumn, = mibViewCtl.mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTableColumn') if isinstance(mibNode, MibTableColumn) or suffix == (0, ): val = mibNode.syntax else: raise error.PySnmpError( 'Found MIB scalar %s but non-scalar given %s' % (mibNode.name + (0, ), ctx['varName'])) else: raise error.PySnmpError('Variable %s has no syntax' % (ctx['varName'], )) else: try: val = self._typeMap[ctx['varType']] except KeyError: raise error.PySnmpError('unsupported SNMP value type \"%s\"' % ctx['varType']) try: val = val.clone(ctx['varValue']) except PyAsn1Error: raise error.PySnmpError(sys.exc_info()[1]) if 'varBinds' not in ctx: ctx['varBinds'] = [(ctx['varName'], val)] else: ctx['varBinds'].append((ctx['varName'], val))
def server_address(self, arg=None): """Set server IP address when copying to/from a remote server. This object can just hold only IPv4 Transport type, it is deprecated and replaced by ccCopyServerAddressRev1." """ oid = self.base_oid + '5.' + self.row if arg is None: return oid else: value = rfc1902.IpAddress(arg) return (oid, value)
def _to_pysnmp(self, value): """ Convert connection plugin object into pysnmp objects """ if value is None: return None if isinstance(value, OctetString): return rfc1902.OctetString(str(value.value)) if isinstance(value, ObjectIdentifier): return rfc1902.ObjectName(str(value.value)) if isinstance(value, Integer32): return rfc1902.Integer32(int(value.value)) if isinstance(value, Counter32): return rfc1902.Counter32(long(value.value)) if isinstance(value, IpAddress): return rfc1902.IpAddress(str(value.value)) if isinstance(value, Gauge32): return rfc1902.Gauge32(long(value.value)) if isinstance(value, TimeTicks): return rfc1902.TimeTicks(long(value.value)) if isinstance(value, Opaque): return rfc1902.Opaque(value.value) # FIXME if isinstance(value, Counter64): return rfc1902.Counter64(str(value.value)) raise SnmpError('Invalid type: %s' % value.__class__.__name__)
docsDevSerialNumber = "1.3.6.1.2.1.69.1.1.4.0" #ubeeRg = '1.3.6.1.4.1.4684.53' #wifiMgmt = '1.3.6.1.4.1.4684.38.2.2.2.1.18' TftpIP = "172.21.1.250" cmIP = input('Input your device IP: ') FWfilesname1 = "UBC1319AA00.alter.1.9.60.1006.15.alt_v1.0.0r18.d30.cdf" FWfilesname2 = "UBC1319AA00.ALTICE-D30.1910.1.9.60.1006.15.alt_v1.0.0r18.d30.cdf" runtime = input('Input total run time of this test: (in minutes) ') timeout = time.time() + 60 * int(runtime) file = open('UG_DG_loop_test.txt', 'w') while True: oldver = Snmp("get", cmIP, "public", "1.3.6.1.2.1.69.1.3.5.0", "") Snmp("set", cmIP, "private", "1.3.6.1.2.1.69.1.3.1.0", rfc1902.IpAddress(TftpIP)) Snmp("set", cmIP, "private", "1.3.6.1.2.1.69.1.3.2.0", rfc1902.OctetString(FWfilesname1)) Snmp("set", cmIP, "private", "1.3.6.1.2.1.69.1.3.3.0", rfc1902.Integer(1)) Operationstatus = Snmp("get", cmIP, "public", "1.3.6.1.2.1.69.1.3.4.0", "") while Operationstatus != "3": Operationstatus = Snmp("get", cmIP, "public", "1.3.6.1.2.1.69.1.3.4.0", "") if Operationstatus == "4": file.write("Upgrade fail! Congestion occur!\n") break time.sleep(10) if Operationstatus == "4": continue latestver = Snmp("get", cmIP, "public", "1.3.6.1.2.1.69.1.3.5.0", "") SerialNum = Snmp("get", cmIP, "public", "1.3.6.1.2.1.69.1.1.4.0", "")
def set(self, name, value, instance=0, context=None, type='i'): ''' snmpojb.set('swDetailsVersion', 1, '05.00.96') ''' oid = '' if self.isDotNotation(name): oid = name # TODO do we try and guess what our value is if we are given dot notation #rfcValue=rfc1902.OctetString(value) # type can be: i INTEGER, u UNSIGNED, s STRING, x HEX STRING, d DECIMAL STRING # n NULLOBJ, o OBJID, t TIMETICKS, a IPADDRESS, b BITS assert (type in 'iusxdnotab' ), "ERROR: Value type {0} not supported".format(type) try: if type == 'i': rfcValue = rfc1902.Integer32(value) elif type == 'u': rfcValue = rfc1902.Unsigned32(value) elif type == 't': rfcValue = rfc1902.TimeTicks(value) elif type == 'a': rfcValue = rfc1902.IpAddress(value) elif type == 'b': rfcValue = rfc1902.Bits(value) elif type == 's': rfcValue = rfc1902.OctetString(value) elif type == 'o': rfcValue = univ.ObjectIdentifier(value) elif type in 'xdn': print 'WARNING: Type ' + type + ' not fully supported (hope default will do)' rfcValue = rfc1902.OctetString(value) else: print "unknown type" except: print("Error in SNMPClient, could not convert {} to type {}" ).format(value, type) else: oid = self.mibs[name].get('oid') # TODO: incode the type type = self.mibs[name].get('type') # TODO: do something similar as if a couple of lines up rfcValue = self.mibs.encode(type, value) #if instance!=0: oid += '.' + str(instance) if context == None: context = self.context if SNMPClient.DEBUG: print "Setting %s (%s) = %s" % (name, oid, str(value)) cmdGen = MyCmdGen() errorIndication, errorStatus, _, varBinds = cmdGen.setCmd( self.agent, context, self.host, self.port, (rfc1902.ObjectName(oid), rfcValue)) if SNMPClient.DEBUG: print 'agent', self.agent print 'context', context print 'host', self.host print 'port', self.port print 'type', type if errorIndication: raise IOError(errorIndication) if errorStatus: raise SNMPError('set on ' + oid + '(' + name + ')', errorStatus) return varBinds[-1][1].prettyPrint()
def pack(self): return rfc1902.IpAddress(str(self._value))
with context('having a hex string with time and date'): with it('returns a timestamp value'): # Note that if only local time is known, then timezone information (fields 8-10) is not present." # See https://cric.grenoble.cnrs.fr/Administrateurs/Outils/MIBS/?oid=1.3.6.1.2.1.16.19.4 data = binascii.unhexlify(b'07E505070B170000') snmp_data = rfc1902.OctetString(data) snmp_value = PySnmpValue(snmp_data) # GMT: Friday, 7 May 2021 11:23:00 expect(snmp_value.to_timestamp()).to(equal(1620386580.0)) with context('when type is IpAddress'): with it('checks value and type'): snmp_data = rfc1902.IpAddress('127.0.0.1') snmp_value = PySnmpValue(snmp_data) expect(snmp_value.value()).to(equal('127.0.0.1')) expect(snmp_value.type_text()).to(equal('IpAddress')) with context('when type is Gauge32'): with it('checks value and type'): snmp_data = rfc1902.Gauge32(42) snmp_value = PySnmpValue(snmp_data) expect(snmp_value.value()).to(equal(42)) expect(snmp_value.type_text()).to(equal('Gauge32'))
def set_ipaddr(self, oid, value): """ Add an IP Address variable to set request """ if not self.is_set(): raise ValueError("Cannot set_int() a non SET request") self.oids.append(RequestOID(oid, self.callback, rfc1902.IpAddress(value)))
def ipaddress_string(self, value): return rfc1902.IpAddress(value)
# Default SNMP context where contextEngineId == SnmpEngineId context.SnmpContext(snmpEngine), # contextName '', # notification name: Generic Trap #6 (enterpriseSpecific) # and Specific Trap 432 '1.3.6.1.4.1.20408.4.1.1.2.0.432', # notification objects instance index None, # additional var-binds holding SNMPv1 TRAP details [ # Uptime value with 12345 (rfc1902.ObjectName('1.3.6.1.2.1.1.3.0'), rfc1902.TimeTicks(12345)), # Agent Address with '127.0.0.1' (rfc1902.ObjectName('1.3.6.1.6.3.18.1.3.0'), rfc1902.IpAddress('127.0.0.1')), # Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 (rfc1902.ObjectName('1.3.6.1.6.3.1.1.4.3.0'), rfc1902.ObjectName('1.3.6.1.4.1.20408.4.1.1.2')), # managed object '1.3.6.1.2.1.1.1.0' = 'my system' (rfc1902.ObjectName('1.3.6.1.2.1.1.1.0'), rfc1902.OctetString('my system')) ])) # Since SNMP TRAP's are unacknowledged, there's nothing to wait for. So we # simulate other loop activities by sleep()'ing. loop.run_until_complete(trollius.sleep(1)) # Clear the event loop loop.close()
def pack(self): return (rfc1902.IpAddress( str(".".join(["{0:d}".format(x) for x in self._value]))))
from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.proto import rfc1902 cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( cmdgen.CommunityData('private', mpModel=0), cmdgen.UdpTransportTarget(('10.90.90.90', 161)), ('1.3.6.1.4.1.171.12.1.2.18.1.1.3.3', rfc1902.IpAddress('10.90.90.100')), ('1.3.6.1.4.1.171.12.1.2.18.1.1.5.3', rfc1902.OctetString('des3810backup.cfg')), ('1.3.6.1.4.1.171.12.1.2.18.1.1.7.3', rfc1902.OctetString('des3810.cfg')), ('1.3.6.1.4.1.171.12.1.2.18.1.1.8.3', rfc1902.Integer(2)), ('1.3.6.1.4.1.171.12.1.2.18.1.1.12.3', rfc1902.Integer(3))) # 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()))