def update(self): """Get the latest data from the remote SNMP capable host.""" from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) errindication, errstatus, errindex, restable = next( getCmd(SnmpEngine(), CommunityData(self._community, mpModel=0), UdpTransportTarget((self._host, self._port)), ContextData(), ObjectType(ObjectIdentity(self._baseoid)))) if errindication: _LOGGER.error("SNMP error: %s", errindication) elif errstatus: _LOGGER.error("SNMP error: %s at %s", errstatus.prettyPrint(), errindex and restable[-1][int(errindex) - 1] or '?') else: for resrow in restable: self.value = resrow[-1]
def open(self, **params): missing_fields = ['ip', 'port'] missing_fields = [ field for field in missing_fields if field not in params.keys() ] if missing_fields: raise KeyError( 'Missing keys in PDU params: {}'.format(missing_fields)) self.params = params self.type = 'pdu' self.ip = self.params['ip'] self.snmp_agent_port = int(self.params['port']) self._community = 'public' self._snmp_engine = SnmpEngine() self._community_data = CommunityData(self._community, mpModel=0) self._udp_transport_target = UdpTransportTarget( (self.ip, self.snmp_agent_port)) self._context = ContextData()
def checkSNMP(): iterator = getCmd( SnmpEngine(), CommunityData( 'public', mpModel=0), #mpModel=0 (SNMPv1), mpModel=1 (SNMPv2c) UdpTransportTarget((self.host_device_input.text(), 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) errorIndication, errorStatus, errorIndex, varBinds = next( iterator) if errorIndication: return f'PASSED: No SNMP response received before timeout on {self.host_device_input.text()}' elif errorStatus: return f'ERROR: There has been an error on {self.host_device_input.text()}' else: for varBind in varBinds: return f'FAILED: SNMP response received on {self.host_device_input.text()}'
def send_snmp_trap(event_context, **kwargs): notification_type = _create_notification_type(event_context) destination_address = kwargs['destination_address'] destination_port = kwargs['destination_port'] community_string = kwargs['community_string'] error_indication, _, _, _ = next( sendNotification( SnmpEngine(), CommunityData(community_string, mpModel=1), UdpTransportTarget((destination_address, destination_port)), ContextData(), NOTIFY_TYPE, notification_type)) logger = setup_logger('cloudify.snmp.snmp_trap') if error_indication: logger.error(error_indication) logger.info( 'Sent SNMP trap of the event: {0} and the execution_id: {1}'.format( event_context['event_type'], event_context['execution_id']))
def make_request(self, req, oid): try: errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(self.secret), UdpTransportTarget((self.server, self.port)), ContextData(), ObjectType(ObjectIdentity(req + str(oid)))), ) except Exception: raise else: if errorIndication: return SNMPError(errorIndication) elif errorStatus: return SNMPError(errorStatus) else: if len(varBinds) == 1: return varBinds[0][1] else: raise SNMPError("Multiple MIB variables returned.")
def get_snmp_without_auth(template_oids, ip, port, snmp_community, snmp_version, timeout, retries): """ :param template_oids: :param ip: :param port: :param snmp_community: :param snmp_version: :param timeout: :param retries: :return: errorIndication, errorStatus, errorIndex, varBinds """ return next( getCmd( SnmpEngine(), CommunityData(snmp_community, mpModel=map_snmp_version[snmp_version]), UdpTransportTarget((ip, port), timeout=timeout, retries=retries), ContextData(), *template_oids))
def polatis_oxc(port, oxc): """ Use SNMP to run cross-connects on a Polatis optical switch. To delete a cross-connect set oxc to 0. Example: polatis_oxc(2,194) connects Ingress port 2 with Egress port 194 """ # logger.warn('Polatis SNMP cross-connect {},{}'.format(port, oxc)) polatis = 'mts01sqsccc.spoc.charterlab.com' oid = '1.3.6.1.4.1.26592.2.2.2.1.2.1.2.{}' g = setCmd( SnmpEngine(), CommunityData('private'), UdpTransportTarget((polatis, 161)), ContextData(), ObjectType( # First Port ObjectIdentity(oid.format(port)), # Second Port Unsigned32(oxc))) next(g)
def snmpCheck(host): iterator = getCmd( SnmpEngine(), CommunityData('public', mpModel=0), #mpModel=0 (SNMPv1), mpModel=1 (SNMPv2c) UdpTransportTarget((host, 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) errorIndication, errorStatus, errorIndex, varBinds = next(iterator) if errorIndication: # print(errorIndication) return f'PASSED: No SNMP response received before timeout on {host}.' elif errorStatus: # print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) return f'ERROR: There has been an error on {host}.' else: for varBind in varBinds: # print(' = '.join([x.prettyPrint() for x in varBind])) return f'FAILED: SNMP response received on {host}.'
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the SNMP sensor.""" from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) name = config.get(CONF_NAME) host = config.get(CONF_HOST) errindication, _, _, _ = next( getCmd(SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget((host, 161)), ContextData(), ObjectType(ObjectIdentity(BASEOID)))) if errindication: _LOGGER.error("Please check the details in the configuration file") return False else: data = BrotherQLData(host) add_devices([BrotherQLSensor(data, name)], True)
def get_SNMP_value(community, ip, MIB, obj, oid): """ Performs an SNMP RO request and retrieves the respons """ errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(community), UdpTransportTarget((ip, 161)), ContextData(), ObjectType(ObjectIdentity(MIB, obj, oid)) )) if errorIndication: raise NetworkManagerReadError("SNMP read error:" + str(errorIndication)) elif errorStatus: raise NetworkManagerReadError('SNMP read error: %s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][ 0] or '?')) else: if len(varBinds) > 1: raise NetworkManagerReadError("SNMP read error: too many values in response") return varBinds[0][1].prettyPrint()
def prepare_authdata(config, snmpversion="2c"): """Prapare authentication data object for various SNMP versions""" # SNMP v1 and v2c if config["community"]: if snmpversion == "2c": model = 1 elif snmpversion == "1": model = 0 authdata = CommunityData(config["community"], mpModel=model) # SNMP v3 else: priv_protocol, auth_protocol = set_snmp_security_protocols(config) authdata = UsmUserData( config["user"], authKey=config["authpassword"], privKey=config["privpassword"], authProtocol=auth_protocol, privProtocol=priv_protocol, ) return authdata
def validate_connection(self): errors = [] snmp_version = 0 if self.source.version == 'v1' else 1 for host in self.source.hosts: host_ = host if '://' in host else f'//{host}' url = urllib.parse.urlparse(host_) iterator = getCmd( SnmpEngine(), CommunityData(self.source.read_community, mpModel=snmp_version), UdpTransportTarget((url.hostname, url.port or SNMP_DEFAULT_PORT), timeout=10, retries=0), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0')), lookupNames=True, lookupMib=True ) for response in iterator: if type(response[0]).__name__ == 'RequestTimedOut': errors.append(f'Couldn\'t get response from `{host}`: {type(response[0]).__name__}') logging.warning(f'Couldn\'t connect to {host}') if len(errors) == len(self.source.hosts): raise ValidationException(errors)
def _fetch_data(pipeline_: Pipeline): snmp_version = 0 if pipeline_.source.version == 'v1' else 1 for host in pipeline_.source.hosts: host_ = host if '://' in host else f'//{host}' url = urlparse(host_) iterator = getCmd(SnmpEngine(), CommunityData(pipeline_.source.read_community, mpModel=snmp_version), UdpTransportTarget( (url.hostname, url.port or SNMP_DEFAULT_PORT), timeout=pipeline_.source.query_timeout, retries=0), ContextData(), *[ ObjectType(ObjectIdentity(mib)) for mib in pipeline_.config['oids'] ], lookupNames=True, lookupMib=True) for i in iterator: yield i, host
def _get(self, *variables): """Get one or more variables via SNMP Args: Tuple with the variables to fetch via SNMP. Returns: List of tuples with the fetched keys and values. """ obj_types = [] for var in variables: if isinstance(var, tuple): obj = ObjectType( ObjectIdentity(self.mib, var[0], var[1]).addMibSource(self.mib_dir)) else: obj = ObjectType( ObjectIdentity(self.mib, var, 0).addMibSource(self.mib_dir)) obj_types.append(obj) errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(self.engine, CommunityData('public'), UdpTransportTarget((self.address, self.port)), ContextData(), *obj_types)) if errorIndication: logger.error(errorIndication) elif errorStatus: logger.error( '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: res = list() for varBind in varBinds: logger.debug(' = '.join([x.prettyPrint() for x in varBind])) res.append(tuple([x.prettyPrint() for x in varBind])) return res
def mainLinkUtilization(deviceList, processNum=1): authData = CommunityData('getgmcc!)', mpModel=1) mibSource = path.join(BASE_DIR, 'pysnmp_fmt/') print(mibSource) mibNodeSet = ( ('IF-MIB', 'ifName', mibSource), ('IF-MIB', 'ifHighSpeed', mibSource), # 单位1000000bit/s即Mb ('IF-MIB', 'ifAlias', mibSource), ('IF-MIB', 'ifHCInOctets', mibSource), # 字节 ('IF-MIB', 'ifHCOutOctets', mibSource), # 字节 ) # 多线程 p = Pool(processNum) resultData = {} for d in deviceList: result = p.apply_async(parseSnmpResult, args=(d, authData, mibNodeSet, mibSource)) # print(result.get()) resultData[d[0]] = result.get() p.close() p.join() return resultData
def port_interaction(self, command, port_number): if command == "on": set_bit = self.onsetting elif command == "off": set_bit = self.offsetting else: raise UnknownCommandException("Unknown command %s." % (command)) transport = UdpTransportTarget((self.hostname, 161)) objecttype = ObjectType( ObjectIdentity(self.mib, self.controlpoint, port_number).addAsn1MibSource( 'http://mibs.snmplabs.com/asn1/@mib@'), int(set_bit)) if self.version == 'snmpv3': if not self.username: raise FailedRequestException("No username set for snmpv3") userdata = UsmUserData(self.username, self.authpass, self.privpass) errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), userdata, transport, ContextData(), objecttype)) elif self.version == 'snmpv1': if not self.community: raise FailedRequestException("No community set for snmpv1") errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), CommunityData(self.community), transport, ContextData(), objecttype)) else: raise FailedRequestException("Unknown snmp version") if errorIndication: raise FailedRequestException(errorIndication) elif errorStatus: raise FailedRequestException(errorStatus) else: for varBind in varBinds: log.debug(' = '.join([x.prettyPrint() for x in varBind])) return True
def get_snmpdata(self, *oids): # передаю сырой oid, потому что с местными MID не смог разобраться нормально result = list() for oid in oids: errorIndication, errorStatus, errorIndex, varBinds = next( getCmd( self.conn, CommunityData(self.env['community'], mpModel=0), UdpTransportTarget((self.host, self.port)), ContextData(), ObjectType(ObjectIdentity(oid))) ) if errorIndication: raise SNMPError(errorIndication) elif errorStatus: raise SNMPStatusError(errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?') else: for varBind in varBinds: result.append(varBind[1].prettyPrint()) return result
def __init__(self, switch_ip: str, community: str = 'public', statsd_host: str = '127.0.0.1', statsd_port: int = 8125, dry_run: bool = False, statsd_prefix: str = 'unifi_switch'): """ UniFi switch to statsd sender :param switch_ip: switch IP address :type switch_ip: str :param community: SNMP v1 community string :type community: str :param statsd_host: statsd server IP or hostname :type statsd_host: str :param statsd_port: statsd port :type statsd_port: int :param dry_run: whether to actually send metrics or just print them :type dry_run: bool :param statsd_prefix: statsd metric prefix :type statsd_prefix: str """ self.statsd: StatsdSender = StatsdSender(statsd_host, statsd_port, statsd_prefix, dry_run=dry_run) self.dry_run: bool = dry_run self.switch_ip: str = switch_ip self.community: str = community logger.debug('Will connect to switch at: %s:161', self.switch_ip) self.engine: SnmpEngine = SnmpEngine() self.cdata: CommunityData = CommunityData(self.community, mpModel=0) self.target: UdpTransportTarget = UdpTransportTarget( (self.switch_ip, 161)) self.if_names: dict = {} self.if_aliases: dict = {} self.if_metric_names: dict = {} self._last_values: dict = {}
def snmpwalk(ipaddress, community, oid): _results = [] for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData(community), UdpTransportTarget((ipaddress, 161)), ContextData(), ObjectType(oid), lexicographicMode=False, lookupMib=True): if errorIndication: raise Exception(f"Error performing snmpwalk: {errorIndication}") if errorStatus: _msg = '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?') raise Exception(f"Error performing snmpget: {_msg}") else: _results.append(varBinds) if len(_results) > 0: return _results return None
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the SNMP sensor.""" from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) config = config.copy() config.update(discovery_info) properties = discovery_info.get('properties', {}) name = config.get(CONF_NAME) or properties.get('ty') host = config.get(CONF_HOST) port = DEFAULT_PORT # config.get(CONF_PORT) community = DEFAULT_COMMUNITY # config.get(CONF_COMMUNITY) baseoid = '1.3.6.1.2.1.25' # config.get(CONF_BASEOID) unit = config.get(CONF_UNIT_OF_MEASUREMENT) version = DEFAULT_VERSION #config.get(CONF_VERSION) accept_errors = config.get(CONF_ACCEPT_ERRORS) default_value = config.get(CONF_DEFAULT_VALUE) value_template = config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass errindication, _, _, _ = next( getCmd(SnmpEngine(), CommunityData(community, mpModel=SNMP_VERSIONS[version]), UdpTransportTarget((host, port)), ContextData(), ObjectType(ObjectIdentity(baseoid)))) if errindication and not accept_errors: _LOGGER.error("Please check the details in the configuration file") return False else: data = SnmpData(host, port, community, baseoid, version, accept_errors, default_value) add_devices([SnmpSensor(data, name, unit, value_template)], True)
def walk(host, oid, data, index): for i, (errorIndication, errorStatus, errorIndex, varBinds) in \ enumerate( nextCmd( SnmpEngine(), CommunityData(SNMP_COMMUNITY, mpModel=1), UdpTransportTarget((host, PORT)), ContextData(), ObjectType(ObjectIdentity(oid)), lexicographicMode=False ) ): if errorIndication: print(errorIndication, file=sys.stderr) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'), file=sys.stderr) break else: for varBind in varBinds: data[index].append(str(varBind).split("=")[1])
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the SNMP sensor.""" from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) community = config.get(CONF_COMMUNITY) baseoid = config.get(CONF_BASEOID) unit = config.get(CONF_UNIT_OF_MEASUREMENT) errindication, _, _, _ = next( getCmd(SnmpEngine(), CommunityData(community, mpModel=0), UdpTransportTarget((host, port)), ContextData(), ObjectType(ObjectIdentity(baseoid)))) if errindication: _LOGGER.error('Please check the details in the configuration file') return False else: data = SnmpData(host, port, community, baseoid) add_devices([SnmpSensor(data, name, unit)])
def get_bulk_snmp(template_oid, ip, snmp_config_data, timeout=1, retries=0, lexicographicMode=False): """[Get bulk Snmp] Arguments: template_oid {[string]} -- [OID] ip {[string]} -- [ip of server(ex: 192.168.88.88)] snmp_config_data {[type]} -- [snmp config get from config file] Keyword Arguments: timeout {int} -- [timeout in seconds] (default: {1}) retries {int} -- [Maximum number of request retries, 0 retries means just a single request.] (default: {0}) lexicographicMode {bool} -- [walk SNMP agent’s MIB till the end (if True), otherwise (if False) stop iteration when all response MIB variables leave the scope of initial MIB variables in varBinds] (default: {False}) Raises: KeyError: [snmp_version input wrong format. Not match in map_snmp_version] KeyError: [property is not exist in snmp_config_data] Returns: [generator] -- [result generator data get by snmp] """ try: snmp_version = snmp_config_data['snmp_version'] port = snmp_config_data['port'] if snmp_version == "v1" or snmp_version == "v2c": snmp_community = snmp_config_data['snmp_community'] snmp_iter = bulkCmd(SnmpEngine(), CommunityData( snmp_community, mpModel=map_snmp_version[snmp_version]), UdpTransportTarget((ip, port), timeout=timeout, retries=retries), ContextData(), 0, 10, ObjectType(ObjectIdentity(template_oid)), lexicographicMode=lexicographicMode) elif snmp_version == "v3": user_name = snmp_config_data['user_name'] auth_key = process_password.decrypt_password( empty_to_none(snmp_config_data['authen_password'])) priv_key = process_password.decrypt_password( empty_to_none(snmp_config_data['priv_password'])) auth_protocol = AUTH_PROTOCOL[empty_to_none( snmp_config_data['authen_protocol'])] priv_protocol = PRIV_PROTOCOL[empty_to_none( snmp_config_data['priv_protocol'])] snmp_iter = bulkCmd(SnmpEngine(), UsmUserData(user_name, authKey=auth_key, privKey=priv_key, authProtocol=auth_protocol, privProtocol=priv_protocol), UdpTransportTarget((ip, port), timeout=timeout, retries=retries), ContextData(), 0, 10, ObjectType(ObjectIdentity(template_oid)), lexicographicMode=lexicographicMode) else: raise KeyError( "'{}' wrong format snmp_version".format(snmp_version)) except KeyError as key_error: raise KeyError("Can not find {} in snmp_config_data".format(key_error)) except Exception as ex: raise ex return snmp_iter
parser.add_argument("-w", "--warning", type=int, default=80, help="I/O usage warning") parser.add_argument("-c", "--critical", type=int, default=95, help="I/O usage critical") args = parser.parse_args() host = args.host community_str = args.community timeout = args.timeout volumes = args.volumes warning_threshold = args.warning / 100 critical_threshold = args.critical / 100 engine = SnmpEngine() context = ContextData() community = CommunityData(community_str, mpModel=1) transport = UdpTransportTarget((host, 161), timeout=timeout) if volumes is not None: exit_status = storage_check(volumes) exit(exit_status) else: print("No mount points defined") exit(exit_status_map["UNKNOWN"])
from pysnmp.hlapi import CommunityData, UsmUserData # SHOULD FAIL a = CommunityData('public', mpModel=0) # SHOULD FAIL insecure = UsmUserData("securityName") # SHOULD FAIL auth_no_priv = UsmUserData("securityName", "authName") # SHOULD PASS less_insecure = UsmUserData("securityName", "authName", "privName")
def __build_poll_targets(self, poll_targets, groups): result = [] if not poll_targets: return result for poll_target in poll_targets: # each poll target needs a 'targets' and a 'oids' list. if "targets" not in poll_target: raise Exception( 'Configuration Error, poll_target does not contain a "targets" list.' ) if "oids" not in poll_target: raise Exception( 'Configuration Error, poll_target does not contain an "oids" list.' ) targets = [] # build a list of PySNMP TransportTargets for target in poll_target["targets"]: # each target needs to have a host if "host" not in target: raise Exception( 'Configuration Error, each target must specify a "host"' ) name = target["host"] # get the port, and create the targets name (a combination of the host:port). port = 161 if "port" in target: port = target["port"] name += ":%d" % port # load timeout and retry values timeout = target.get("timeout", 1) retries = target.get("retries", 3) # create the transport transport = UdpTransportTarget((target["host"], port), timeout=timeout, retries=retries) # get the version - default to v2, unless the 'user' field is specified, then default # to v3 version = "snmpv2" if "user" in target: version = "snmpv3" if "version" in target: version = target["version"].lower() # Sanity check - if 'user' is provided, version must be 'snmpv3' if "user" in target and version != "snmpv3": raise Exception( "Configuration Error, user authentication is only supported for SNMPv3" ) # depedning on the version, create the appropriate authentication object auth = None if version == "snmpv1": auth = CommunityData("public", mpModel=0) elif version == "snmpv3": auth = self.__build_snmpv3_user(target) else: auth = CommunityData("public") # add the transport, auth and name to the list of targets targets.append({ "transport": transport, "auth": auth, "name": name }) # build a list of oids for the targets oids = [] for oid in poll_target["oids"]: # the oid groups need to be in the previous list of oids if oid not in groups: raise Exception( "Configuration Error, '%s' is not a valid oid group" % six.text_type(oid)) oids += groups[oid] if not oids: raise Exception( "Configuration Error, no oid groups specified for poll_target" ) # add our target list and oid list to the list of poll_targets result.append({"targets": targets, "oids": [oids]}) return result
def get_snmp_data(device): try: device_data = [] if(device["type"].upper() == 'DX-SNMP'): community = device["attributes"]["community"] host_name = device["attributes"]["host_name"] port = device["attributes"]["port"] oids = device["attributes"]["oid"] if (device["attributes"]["snmp_version"] == 1): snmp_version = 0 elif (device["attributes"]["snmp_version"] == 2): snmp_version = 1 if(host_name != ""): if(oids != ""): if(community != ""): if(snmp_version != ""): print("--- Reading SNMP Device Data ---") for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData( community, mpModel=snmp_version), UdpTransportTarget( (host_name, port)), ContextData(), ObjectType(ObjectIdentity(oids))): if errorIndication: print("--- Error: " + str(errorIndication)+" ---") return device_data, 1 elif errorStatus: print("--- Error ---") print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) print("--- Error End ---") return device_data, 1 else: for varBind in varBinds: data_point = [x.prettyPrint() for x in varBind] device_data.append( { data_point[0].split(":")[-1].replace(".", "_"): data_point[1] } ) print("--- Successfully Read SNMP Device Data ---") return device_data, 0 else: print( 'Device attribute missing or invalid: snmp_version') return [], 1 else: print('Device attribute missing or invalid: community') return [], 1 else: print('Device attribute missing or invalid: oid') return [], 1 else: print('Device attribute missing or invalid: host_name') return [], 1 else: print('Device not of type DX-SNMP') return [], 1 except Exception as e: # print(device) print('Error occured while reading snmp device: ', device['id'], e) # traceback.print_tb(e.__traceback__) return device_data, 1
from pysnmp.hlapi import getCmd, SnmpEngine, CommunityData, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity errorIndication, errorStatus, errorIndex, varBinds = next( getCmd( SnmpEngine(), CommunityData('secret'), UdpTransportTarget(('1.1.1.1', 161)), ContextData(), ObjectType( ObjectIdentity('SNMPv2-SMI', 'enterprises', "9.9.512.1.1.1.1.3.1")))) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind]))
from pysnmp.hlapi import setCmd, SnmpEngine, CommunityData from pysnmp.hlapi import UdpTransportTarget, ContextData, ObjectType from pysnmp.hlapi import ObjectIdentity, OctetString import credentials2 as cred # MibVariable oid = ObjectIdentity('SNMPv2-MIB', 'sysName', 0) target_addr = (cred.ip, cred.snmp_port) snmp_engine_obj = SnmpEngine() com_data_obj = CommunityData(cred.community_string) udp_transport_target_obj = UdpTransportTarget(target_addr) context_data_obj = ContextData() # otype_oid = ObjectType(oid, OctetString("New description")) otype_oid = ObjectType(oid, "New system name") gen = setCmd(snmp_engine_obj, com_data_obj, udp_transport_target_obj, context_data_obj, otype_oid, lookupNames=False, lookupValues=True) *errorInformation, varBinds = next(gen) # errorIndication, errorStatus, errorIndex = errorInformation # print(errorInformation) # [None, 0, 0] for rfc1902obj in varBinds: print(rfc1902obj.prettyPrint())
def snmp_getcmd(community, ip, port, OID): return (getCmd(SnmpEngine(), CommunityData(community), UdpTransportTarget((ip, port), timeout=0.9, retries=0), ContextData(), ObjectType(ObjectIdentity(OID))))