Пример #1
0
def get_snmp_data(config, *args, snmp_engine=SnmpEngine(), snmpversion="2c"):
    """Retrieve necessary data via SNMP"""

    authdata = prepare_authdata(config, snmpversion)

    target = UdpTransportTarget((config["host"], config["port"]))

    error_indication, error_status, error_index, var_binds = next(
        getCmd(snmp_engine, authdata, target, ContextData(), *args))
    if error_indication:
        raise ValueError(error_indication)
    elif error_status:
        status = error_status.prettyPrint()
        index = error_index and var_binds[int(error_index) - 1][0] or "?"
        raise ValueError(f"{status} at {index}")

    return var_binds
Пример #2
0
def snmpGet(ip, oid, community='public', versao_snmp=0, porta=161):
    errorIndication, errorStatus, errorIndex, varBinds = next(
        getCmd(SnmpEngine(),
               CommunityData(community, mpModel=versao_snmp),
               UdpTransportTarget((ip, porta)),
               ContextData(),
               ObjectType(ObjectIdentity(oid)))
    )

    if errorIndication:
        return(str(errorIndication))
    elif errorStatus:
        return('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        for varBind in varBinds:
            return (' = '.join([x.prettyPrint() for x in varBind])).split(' = ')[1]
Пример #3
0
 def get(host,oid,community):
     errorIndication, errorStatus, errorIndex, varBinds = next(
         getCmd(SnmpEngine(),
             CommunityData(community, mpModel=0),
             UdpTransportTarget((host, 161)),
             ContextData(),
             ObjectType(ObjectIdentity(oid)))
     )
     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(varBind[1])
     return varBind[1]
Пример #4
0
    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]
Пример #5
0
 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()
Пример #6
0
            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()}'
Пример #7
0
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']))
Пример #8
0
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)
Пример #9
0
    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 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 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))
Пример #12
0
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)
Пример #13
0
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()
Пример #14
0
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
Пример #15
0
 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)
Пример #16
0
    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
Пример #17
0
    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
Пример #18
0
    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 = {}
Пример #19
0
 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
Пример #20
0
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
Пример #21
0
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)
Пример #22
0
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)])
Пример #23
0
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])
Пример #24
0
    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"])
Пример #25
0
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]))
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
Пример #27
0
def snmp_getcmd(community, ip, port, OID):
    return (getCmd(SnmpEngine(), CommunityData(community),
                   UdpTransportTarget((ip, port), timeout=0.9, retries=0),
                   ContextData(), ObjectType(ObjectIdentity(OID))))
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())
Пример #29
0
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
Пример #30
0
    def do_work(
        self,
        ir: InventoryRecord,
        walk: bool = False,
        profiles: List[str] = None,
        walked_first_time=True,
    ):
        retry = False
        address = transform_address_to_key(ir.address, ir.port)

        if time.time() - self.last_modified > PROFILES_RELOAD_DELAY:
            self.profiles = load_profiles()
            self.last_modified = time.time()
            logger.debug("Profiles reloaded")

        varbinds_get, get_mapping, varbinds_bulk, bulk_mapping = self.get_var_binds(
            address,
            walk=walk,
            profiles=profiles,
            walked_first_time=walked_first_time)

        authData = GetAuth(logger, ir, self.snmpEngine)
        contextData = get_context_data()

        transport = UdpTransportTarget((ir.address, ir.port),
                                       timeout=UDP_CONNECTION_TIMEOUT)

        metrics: Dict[str, Any] = {}
        if not varbinds_get and not varbinds_bulk:
            logger.info(f"No work to do for {address}")
            return False, {}

        if varbinds_bulk:

            for (
                    errorIndication,
                    errorStatus,
                    errorIndex,
                    varBindTable,
            ) in bulkCmd(
                    self.snmpEngine,
                    authData,
                    transport,
                    contextData,
                    1,
                    10,
                    *varbinds_bulk,
                    lexicographicMode=False,
                    ignoreNonIncreasingOid=is_increasing_oids_ignored(
                        ir.address, ir.port),
            ):
                if not _any_failure_happened(
                        errorIndication,
                        errorStatus,
                        errorIndex,
                        varBindTable,
                        ir.address,
                        walk,
                ):
                    tmp_retry, tmp_mibs, _ = self.process_snmp_data(
                        varBindTable, metrics, address, bulk_mapping)
                    if tmp_mibs:
                        self.load_mibs(tmp_mibs)
                        self.process_snmp_data(varBindTable, metrics, address,
                                               bulk_mapping)

        if varbinds_get:
            for (
                    errorIndication,
                    errorStatus,
                    errorIndex,
                    varBindTable,
            ) in getCmd(self.snmpEngine, authData, transport, contextData,
                        *varbinds_get):
                if not _any_failure_happened(
                        errorIndication,
                        errorStatus,
                        errorIndex,
                        varBindTable,
                        ir.address,
                        walk,
                ):
                    self.process_snmp_data(varBindTable, metrics, address,
                                           get_mapping)

        for group_key, metric in metrics.items():
            if "profiles" in metrics[group_key]:
                metrics[group_key]["profiles"] = ",".join(
                    metrics[group_key]["profiles"])

        return retry, metrics