예제 #1
0
    def _send_snmp_trap(host, var_binds, alarm_oid):

        host_details = host['host']

        send_to = str(host_details.get('send_to'))
        port = str(host_details.get('port', 162))
        community_str = host_details.get('community', 'public')

        if not (send_to and IP_PAT.match(send_to) and PORT_PAT.match(port)):
            LOG.info("Vitrage snmp Info: an SNMP target host was not"
                     " configured correctly")
            return

        LOG.debug("Vitrage snmp Debug: Trap parameters: send_to: %s, "
                  "port: %s, community string: %s" %
                  (send_to, port, community_str))

        error_indication, error_status, error_index, var_bins = next(
            sendNotification(
                SnmpEngine(), CommunityData(community_str, mpModel=1),
                UdpTransportTarget((send_to, port)), ContextData(), 'trap',
                NotificationType(
                    ObjectIdentity(alarm_oid), ).addVarBinds(*var_binds)))

        if error_indication:
            LOG.error('Vitrage snmp Error: Notification not sent: %s' %
                      error_indication)
        elif error_status:
            LOG.error('Vitrage snmp Error: Notification Receiver '
                      'returned error: %s @%s' % (error_status, error_index))
예제 #2
0
def _snmp_walk(host, community, oid):
    assert host, "host must be defined."
    assert community, "community must be defined."
    assert oid, "oid must be defined."
    assert isinstance(oid, ObjectType), "oid must be of ObjectType"

    for errorIndication, errorStatus, errorIndex, varBinds in nextCmd(
            SnmpEngine(),
            CommunityData(community, mpModel=1),
            UdpTransportTarget((host, 161)),
            ContextData(),
            oid,
            ignoreNonIncreasingOid=True,
            lookupMib=True,
            lexicographicMode=False):

        if errorIndication:
            logger.error(errorIndication)
        else:
            if errorStatus:
                raise Exception('%s at %s' % (
                    errorStatus.prettyPrint(),
                    errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
            else:
                for name, val in varBinds:
                    yield name.prettyPrint(), val.prettyPrint()
예제 #3
0
def getSnmpEngine(engineId=None):
    """Create SNMP engine instance.

    Args:
        engineId (str): SNMP engine ID as a ASCII or hex string

    Returns:
        object: SNMP engine object
    """
    if engineId:
        engineId = engineId.replace(':', '')

        if engineId.startswith('0x') or engineId.startswith('0X'):
            engineId = engineId[2:]

        engineId = OctetString(hexValue=engineId)

    return SnmpEngine(snmpEngineID=engineId)
예제 #4
0
파일: snmp.py 프로젝트: anodot/daria
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
예제 #5
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)
예제 #6
0
                        "--critical",
                        type=list,
                        default=[95, 95],
                        help="I/O usage critical")
    args = parser.parse_args()

    host = args.host
    hostname = args.icingahostname
    community_str = args.community
    timeout = args.timeout
    interfaces = args.interfaces
    new_int_name_format = args.newintformat
    check_if_status = args.checkstatus
    get_vlan = args.vlan
    warning_threshold = args.warning
    critical_threshold = args.critical
    octects_only = args.octectsonly

    engine = SnmpEngine()
    context = ContextData()
    community = CommunityData(community_str, mpModel=1)
    transport = UdpTransportTarget((host, 161), timeout=timeout)

    if interfaces is not None:
        exit_status = if_check(interfaces)
        exit(exit_status)
    else:
        # if_update()
        print("No mount points defined")
        exit(exit_status_map["UNKNOWN"])
예제 #7
0
 def __init__(self):
     SnmpEngine.__init__(self,
                         snmpEngineID=None,
                         maxMessageSize=65507,
                         msgAndPduDsp=None)
예제 #8
0
 def __init__(self):
     SnmpEngine.__init__(self, snmpEngineID=None, maxMessageSize=65507, msgAndPduDsp=None)