Ejemplo n.º 1
0
    def __init__(self, host,
                 community="public", version=2,
                 secname=None,
                 authprotocol=None,
                 authpassword=None,
                 privprotocol=None,
                 privpassword=None):
        """Create a new SNMP session.

        :param host: The hostname or IP address of the agent to
            connect to. Optionally, the port can be specified
            separated with a double colon.
        :type host: str
        :param community: The community to transmit to the agent for
            authorization purpose. This parameter is ignored if the
            specified version is 3.
        :type community: str
        :param version: The SNMP version to use to talk with the
            agent. Possible values are `1`, `2` (community-based) or
            `3`.
        :type version: int
        :param secname: Security name to use for SNMPv3 only.
        :type secname: str
        :param authprotocol: Authorization protocol to use for
            SNMPv3. This can be `None` or either the string `SHA` or
            `MD5`.
        :type authprotocol: None or str
        :param authpassword: Authorization password if authorization
            protocol is not `None`.
        :type authpassword: str
        :param privprotocol: Privacy protocol to use for SNMPv3. This
            can be `None` or either the string `AES`, `AES128`,
            `AES192`, `AES256` or `3DES`.
        :type privprotocol: None or str
        :param privpassword: Privacy password if privacy protocol is
            not `None`.
        :type privpassword: str
        """
        self._host = host
        self._version = version
        self._cmdgen = cmdgen.CommandGenerator()

        # Put authentication stuff in self._auth
        if version in [1, 2]:
            self._auth = cmdgen.CommunityData(
                community, community, version - 1)
        elif version == 3:
            if secname is None:
                secname = community
            try:
                authprotocol = {
                    None: cmdgen.usmNoAuthProtocol,
                    "MD5": cmdgen.usmHMACMD5AuthProtocol,
                    "SHA": cmdgen.usmHMACSHAAuthProtocol,
                    "SHA1": cmdgen.usmHMACSHAAuthProtocol
                }[authprotocol]
            except KeyError:
                raise ValueError("{0} is not an acceptable authentication "
                                 "protocol".format(authprotocol))
            try:
                privprotocol = {
                    None: cmdgen.usmNoPrivProtocol,
                    "DES": cmdgen.usmDESPrivProtocol,
                    "3DES": cmdgen.usm3DESEDEPrivProtocol,
                    "AES": cmdgen.usmAesCfb128Protocol,
                    "AES128": cmdgen.usmAesCfb128Protocol,
                    "AES192": cmdgen.usmAesCfb192Protocol,
                    "AES256": cmdgen.usmAesCfb256Protocol,
                }[privprotocol]
            except KeyError:
                raise ValueError("{0} is not an acceptable privacy "
                                 "protocol".format(privprotocol))
            self._auth = cmdgen.UsmUserData(secname,
                                            authpassword,
                                            privpassword,
                                            authprotocol,
                                            privprotocol)
        else:
            raise ValueError("unsupported SNMP version {0}".format(version))

        # Put transport stuff into self._transport
        host, port = host.partition(":")[::2]
        if not port:
            port = 161
        self._transport = cmdgen.UdpTransportTarget((host, int(port)))

        # Bulk stuff
        self.bulk = 40
Ejemplo n.º 2
0
from pysnmp.entity.rfc3413.oneliner import cmdgen, ntforg
from pysnmp.proto.api import v2c


def cbFun(sendRequestHandle, errorIndication, cbCtx):
    print 'sendRequestHandle =', sendRequestHandle
    print 'errorIndication =', errorIndication
    print 'cbCtx =', cbCtx


asynNotificationOriginator = ntforg.AsynNotificationOriginator()
# This is a non-blocking call
sendRequestHandle = asynNotificationOriginator.asyncSendNotification(
    cmdgen.UsmUserData('my-user', 'my-authkey', 'my-privkey'),
    cmdgen.UdpTransportTarget(
        ('localhost', 162)), 'inform', ('SNMPv2-MIB', 'coldStart'),
    ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.TimeTicks(44100)), (cbFun, None))
print sendRequestHandle

asynNotificationOriginator.snmpEngine.transportDispatcher.runDispatcher()
Ejemplo n.º 3
0
def do_run():

    config = get_input_config()

    activation_key = config.get("activation_key")
    app_name = "SNMP Modular Input"

    m = hashlib.md5()
    m.update((app_name))
    if not m.hexdigest().upper() == activation_key.upper():
        logging.error("FATAL Activation key for App '%s' failed" % app_name)
        sys.exit(2)

    #params
    snmp_mode = config.get("snmp_mode", "")

    destination_list = config.get("destination")

    if not destination_list is None:
        destinations = map(str, destination_list.split(","))
        #trim any whitespace using a list comprehension
        destinations = [x.strip(' ') for x in destinations]

    port = int(config.get("port", 161))
    snmpinterval = int(config.get("snmpinterval", 60))
    timeout_val = float(config.get("timeout", 1.0))
    num_retries = int(config.get("retries", 5))
    ipv6 = int(config.get("ipv6", 0))

    try:
        # update all the root StreamHandlers with a new formatter that includes the config information
        for h in logging.root.handlers:
            if isinstance(h, logging.StreamHandler):
                h.setFormatter(
                    logging.Formatter(
                        '%(levelname)s %(message)s snmp_stanza:{0}'.format(
                            config.get("name"))))

    except:  # catch *all* exceptions
        e = sys.exc_info()[1]
        logging.error("Couldn't update logging templates: %s host:'" % str(e))

    response_handler_args = {}
    response_handler_args_str = config.get("response_handler_args")
    if not response_handler_args_str is None:
        response_handler_args = dict(
            (k.strip(), v.strip())
            for k, v in (item.split('=')
                         for item in response_handler_args_str.split(',')))

    response_handler = config.get("response_handler", "DefaultResponseHandler")
    module = __import__("responsehandlers")
    class_ = getattr(module, response_handler)

    global RESPONSE_HANDLER_INSTANCE
    RESPONSE_HANDLER_INSTANCE = class_(**response_handler_args)

    #snmp 1 and 2C params
    snmp_version = config.get("snmp_version", "2C")

    communitystring = config.get("communitystring", "public")

    v3_securityName = config.get("v3_securityName", "")
    v3_authKey = config.get("v3_authKey", None)
    v3_privKey = config.get("v3_privKey", None)
    v3_authProtocol_str = config.get("v3_authProtocol",
                                     "usmHMACMD5AuthProtocol")
    v3_privProtocol_str = config.get("v3_privProtocol", "usmDESPrivProtocol")

    if v3_authProtocol_str == "usmHMACMD5AuthProtocol":
        v3_authProtocol = cmdgen.usmHMACMD5AuthProtocol
    elif v3_authProtocol_str == "usmHMACSHAAuthProtocol":
        v3_authProtocol = cmdgen.usmHMACSHAAuthProtocol
    elif v3_authProtocol_str == "usmNoAuthProtocol":
        v3_authProtocol = cmdgen.usmNoAuthProtocol
    else:
        v3_authProtocol = cmdgen.usmNoAuthProtocol

    if v3_privProtocol_str == "usmDESPrivProtocol":
        v3_privProtocol = cmdgen.usmDESPrivProtocol
    elif v3_privProtocol_str == "usm3DESEDEPrivProtocol":
        v3_privProtocol = cmdgen.usm3DESEDEPrivProtocol
    elif v3_privProtocol_str == "usmAesCfb128Protocol":
        v3_privProtocol = cmdgen.usmAesCfb128Protocol
    elif v3_privProtocol_str == "usmAesCfb192Protocol":
        v3_privProtocol = cmdgen.usmAesCfb192Protocol
    elif v3_privProtocol_str == "usmAesCfb256Protocol":
        v3_privProtocol = cmdgen.usmAesCfb256Protocol
    elif v3_privProtocol_str == "usmNoPrivProtocol":
        v3_privProtocol = cmdgen.usmNoPrivProtocol
    else:
        v3_privProtocol = cmdgen.usmNoPrivProtocol

    #object names to poll
    object_names = config.get("object_names")
    if not object_names is None:
        oid_args = map(str, object_names.split(","))
        #trim any whitespace using a list comprehension
        oid_args = [x.strip(' ') for x in oid_args]

    #GET BULK params
    do_subtree = int(config.get("do_get_subtree", 0))
    do_bulk = int(config.get("do_bulk_get", 0))
    split_bulk_output = int(config.get("split_bulk_output", 0))
    non_repeaters = int(config.get("non_repeaters", 0))
    max_repetitions = int(config.get("max_repetitions", 25))

    #TRAP listener params
    listen_traps = int(config.get("listen_traps", 0))
    #some backwards compatibility gymnastics
    if snmp_mode == 'traps':
        listen_traps = 1

    trap_port = int(config.get("trap_port", 162))
    trap_host = config.get("trap_host", "localhost")

    global trap_rdns
    trap_rdns = int(config.get("trap_rdns", 0))

    #MIBs to load
    mib_names = config.get("mib_names")
    mib_names_args = None
    if not mib_names is None:
        mib_names_args = map(str, mib_names.split(","))
        #trim any whitespace using a list comprehension
        mib_names_args = [x.strip(' ') for x in mib_names_args]

    #load in custom MIBS
    cmdGen = cmdgen.CommandGenerator()

    mibBuilder = cmdGen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    mibSources = (builder.DirMibSource(mib_egg_dir), )

    for filename in os.listdir(mib_egg_dir):
        if filename.endswith(".egg"):
            mibSources = mibSources + (builder.ZipMibSource(filename), )

    mibSources = mibBuilder.getMibSources() + mibSources
    mibBuilder.setMibSources(*mibSources)

    if mib_names_args:
        mibBuilder.loadModules(*mib_names_args)

    global mibView
    mibView = view.MibViewController(mibBuilder)

    if listen_traps:
        if snmp_version == "1" or snmp_version == "2C":
            trapThread = TrapThread(trap_port, trap_host, ipv6)
            trapThread.start()
        if snmp_version == "3":
            trapThread = V3TrapThread(trap_port, trap_host, ipv6,
                                      v3_securityName, v3_authKey,
                                      v3_authProtocol, v3_privKey,
                                      v3_privProtocol)
            trapThread.start()

    if not (object_names is None) and not (destination_list is None):

        mp_model_val = 1

        for destination in destinations:
            if snmp_version == "1":
                mp_model_val = 0

            if snmp_version == "3":
                security_object = cmdgen.UsmUserData(
                    v3_securityName,
                    authKey=v3_authKey,
                    privKey=v3_privKey,
                    authProtocol=v3_authProtocol,
                    privProtocol=v3_privProtocol)
            else:
                security_object = cmdgen.CommunityData(communitystring,
                                                       mpModel=mp_model_val)

            if ipv6:
                transport = cmdgen.Udp6TransportTarget((destination, port),
                                                       timeout=timeout_val,
                                                       retries=num_retries)
            else:
                transport = cmdgen.UdpTransportTarget((destination, port),
                                                      timeout=timeout_val,
                                                      retries=num_retries)

            apt = AttributePollerThread(cmdGen, destination, port, transport,
                                        snmp_version, do_bulk, do_subtree,
                                        security_object, snmpinterval,
                                        non_repeaters, max_repetitions,
                                        oid_args, split_bulk_output)
            apt.start()
Ejemplo n.º 4
0
def validate_connectivity(alert_source, plain_auth_key, plain_priv_key):
    # Fill optional parameters with default values if not set in input
    if not alert_source.get('port'):
        alert_source['port'] = constants.DEFAULT_SNMP_CONNECT_PORT

    if not alert_source.get('context_name'):
        alert_source['context_name'] = None

    if not alert_source.get('retry_num'):
        alert_source['retry_num'] = constants.DEFAULT_SNMP_RETRY_NUM

    if not alert_source.get('expiration'):
        alert_source['expiration'] = constants.DEFAULT_SNMP_EXPIRATION_TIME

    if CONF.snmp_validation_enabled is False:
        return alert_source

    cmd_gen = cmdgen.CommandGenerator()

    version = alert_source.get('version')
    error_indication = None

    # Connect to alert source through snmp get to check the configuration
    try:
        if version.lower() == 'snmpv3':
            auth_protocol = None
            privacy_protocol = None
            if alert_source['auth_protocol'] is not None:
                auth_protocol = constants.AUTH_PROTOCOL_MAP.get(
                    alert_source['auth_protocol'].lower())
            if alert_source['privacy_protocol'] is not None:
                privacy_protocol = constants.PRIVACY_PROTOCOL_MAP.get(
                    alert_source['privacy_protocol'].lower())

            error_indication, __, __, __ = cmd_gen.getCmd(
                cmdgen.UsmUserData(alert_source['username'],
                                   authKey=plain_auth_key,
                                   privKey=plain_priv_key,
                                   authProtocol=auth_protocol,
                                   privProtocol=privacy_protocol),
                cmdgen.UdpTransportTarget(
                    (alert_source['host'], alert_source['port']),
                    timeout=alert_source['expiration'],
                    retries=alert_source['retry_num']),
                constants.SNMP_QUERY_OID,
            )
        else:
            error_indication, __, __, __ = cmd_gen.getCmd(
                cmdgen.CommunityData(alert_source['community_string'],
                                     contextName=alert_source['context_name']),
                cmdgen.UdpTransportTarget(
                    (alert_source['host'], alert_source['port']),
                    timeout=alert_source['expiration'],
                    retries=alert_source['retry_num']),
                constants.SNMP_QUERY_OID,
            )

        if not error_indication:
            return alert_source

        # Prepare exception with error_indication
        msg = (_("configuration validation failed with alert source for "
                 "reason: %s.") % error_indication)
    except Exception as e:
        msg = (_("configuration validation failed with alert source for "
                 "reason: %s.") % six.text_type(e))

    # Since validation occur error, raise exception
    raise exception.InvalidResults(msg)
Ejemplo n.º 5
0
def main():
    module = AnsibleModule(argument_spec=dict(
        host=dict(required=True),
        timeout=dict(reqired=False, type='int', default=5),
        version=dict(required=True, choices=['v2', 'v2c', 'v3']),
        community=dict(required=False, default=False),
        username=dict(required=False),
        level=dict(required=False, choices=['authNoPriv', 'authPriv']),
        integrity=dict(required=False, choices=['md5', 'sha']),
        privacy=dict(required=False, choices=['des', 'aes']),
        authkey=dict(required=False),
        privkey=dict(required=False),
        is_dell=dict(required=False, default=False, type='bool'),
        is_eos=dict(required=False, default=False, type='bool'),
        removeplaceholder=dict(required=False)),
                           required_together=(
                               ['username', 'level', 'integrity', 'authkey'],
                               ['privacy', 'privkey'],
                           ),
                           supports_check_mode=False)

    m_args = module.params

    if not has_pysnmp:
        module.fail_json(msg='Missing required pysnmp module (check docs)')

    cmdGen = cmdgen.CommandGenerator()

    # Verify that we receive a community when using snmp v2
    if m_args['version'] == "v2" or m_args['version'] == "v2c":
        if m_args['community'] == False:
            module.fail_json(msg='Community not set when using snmp version 2')

    if m_args['version'] == "v3":
        if m_args['username'] == None:
            module.fail_json(msg='Username not set when using snmp version 3')

        if m_args['level'] == "authPriv" and m_args['privacy'] == None:
            module.fail_json(
                msg='Privacy algorithm not set when using authPriv')

        if m_args['integrity'] == "sha":
            integrity_proto = cmdgen.usmHMACSHAAuthProtocol
        elif m_args['integrity'] == "md5":
            integrity_proto = cmdgen.usmHMACMD5AuthProtocol

        if m_args['privacy'] == "aes":
            privacy_proto = cmdgen.usmAesCfb128Protocol
        elif m_args['privacy'] == "des":
            privacy_proto = cmdgen.usmDESPrivProtocol

    # Use SNMP Version 2
    if m_args['version'] == "v2" or m_args['version'] == "v2c":
        snmp_auth = cmdgen.CommunityData(m_args['community'])

    # Use SNMP Version 3 with authNoPriv
    elif m_args['level'] == "authNoPriv":
        snmp_auth = cmdgen.UsmUserData(m_args['username'],
                                       authKey=m_args['authkey'],
                                       authProtocol=integrity_proto)

    # Use SNMP Version 3 with authPriv
    else:
        snmp_auth = cmdgen.UsmUserData(m_args['username'],
                                       authKey=m_args['authkey'],
                                       privKey=m_args['privkey'],
                                       authProtocol=integrity_proto,
                                       privProtocol=privacy_proto)

    # Use p to prefix OIDs with a dot for polling
    p = DefineOid(dotprefix=True)
    # Use v without a prefix to use with return values
    v = DefineOid(dotprefix=False)

    Tree = lambda: defaultdict(Tree)

    results = Tree()

    # Getting system description could take more than 1 second on some Dell platform
    # (e.g. S6000) when cpu utilization is high, increse timeout to tolerate the delay.
    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161),
                                  timeout=m_args['timeout']),
        cmdgen.MibVariable(p.sysDescr, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) +
                         ' querying system description.')

    for oid, val in varBinds:
        current_oid = oid.prettyPrint()
        current_val = val.prettyPrint()
        if current_oid == v.sysDescr:
            results['ansible_sysdescr'] = decode_hex(current_val)

    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.sysObjectId, ),
        cmdgen.MibVariable(p.sysUpTime, ),
        cmdgen.MibVariable(p.sysContact, ),
        cmdgen.MibVariable(p.sysName, ),
        cmdgen.MibVariable(p.sysLocation, ),
        lookupMib=False,
        lexicographicMode=False)

    if errorIndication:
        module.fail_json(msg=str(errorIndication) +
                         ' querying system infomation.')

    for oid, val in varBinds:
        current_oid = oid.prettyPrint()
        current_val = val.prettyPrint()
        if current_oid == v.sysObjectId:
            results['ansible_sysobjectid'] = current_val
        elif current_oid == v.sysUpTime:
            results['ansible_sysuptime'] = current_val
        elif current_oid == v.sysContact:
            results['ansible_syscontact'] = current_val
        elif current_oid == v.sysName:
            results['ansible_sysname'] = current_val
        elif current_oid == v.sysLocation:
            results['ansible_syslocation'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.ifIndex, ),
        cmdgen.MibVariable(p.ifDescr, ),
        cmdgen.MibVariable(p.ifType, ),
        cmdgen.MibVariable(p.ifMtu, ),
        cmdgen.MibVariable(p.ifSpeed, ),
        cmdgen.MibVariable(p.ifPhysAddress, ),
        cmdgen.MibVariable(p.ifAdminStatus, ),
        cmdgen.MibVariable(p.ifOperStatus, ),
        cmdgen.MibVariable(p.ifHighSpeed, ),
        cmdgen.MibVariable(p.ipAdEntAddr, ),
        cmdgen.MibVariable(p.ipAdEntIfIndex, ),
        cmdgen.MibVariable(p.ipAdEntNetMask, ),
        cmdgen.MibVariable(p.ifAlias, ),
        lookupMib=False,
        lexicographicMode=False)

    if errorIndication:
        module.fail_json(msg=str(errorIndication) +
                         ' querying interface details')

    interface_indexes = []

    all_ipv4_addresses = []
    ipv4_networks = Tree()

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.ifIndex in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex]['ifindex'] = current_val
                interface_indexes.append(ifIndex)
            if v.ifDescr in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex]['name'] = current_val
            if v.ifType in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex]['type'] = current_val
            if v.ifMtu in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex]['mtu'] = current_val
            if v.ifSpeed in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex]['speed'] = current_val
            if v.ifPhysAddress in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex]['mac'] = decode_mac(
                    current_val)
            if v.ifAdminStatus in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'adminstatus'] = lookup_adminstatus(int(current_val))
            if v.ifOperStatus in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'operstatus'] = lookup_operstatus(int(current_val))
            if v.ifHighSpeed in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'ifHighSpeed'] = current_val
            if v.ipAdEntAddr in current_oid:
                curIPList = current_oid.rsplit('.', 4)[-4:]
                curIP = ".".join(curIPList)
                ipv4_networks[curIP]['address'] = current_val
                all_ipv4_addresses.append(current_val)
            if v.ipAdEntIfIndex in current_oid:
                curIPList = current_oid.rsplit('.', 4)[-4:]
                curIP = ".".join(curIPList)
                ipv4_networks[curIP]['interface'] = current_val
            if v.ipAdEntNetMask in current_oid:
                curIPList = current_oid.rsplit('.', 4)[-4:]
                curIP = ".".join(curIPList)
                ipv4_networks[curIP]['netmask'] = current_val
            if v.ifAlias in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'description'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.ifInDiscards, ),
        cmdgen.MibVariable(p.ifOutDiscards, ),
        cmdgen.MibVariable(p.ifInErrors, ),
        cmdgen.MibVariable(p.ifOutErrors, ),
        cmdgen.MibVariable(p.ifHCInOctets, ),
        cmdgen.MibVariable(p.ifHCOutOctets, ),
        cmdgen.MibVariable(p.ifInUcastPkts, ),
        cmdgen.MibVariable(p.ifOutUcastPkts, ),
        lookupMib=False,
        lexicographicMode=False)

    if errorIndication:
        module.fail_json(msg=str(errorIndication) +
                         ' querying interface counters')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.ifInDiscards in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'ifInDiscards'] = current_val
            if v.ifOutDiscards in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'ifOutDiscards'] = current_val
            if v.ifInErrors in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex]['ifInErrors'] = current_val
            if v.ifOutErrors in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'ifOutErrors'] = current_val
            if v.ifHCInOctets in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'ifHCInOctets'] = current_val
            if v.ifHCOutOctets in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'ifHCOutOctets'] = current_val
            if v.ifInUcastPkts in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'ifInUcastPkts'] = current_val
            if v.ifOutUcastPkts in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'ifOutUcastPkts'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.entPhysDescr, ),
        cmdgen.MibVariable(p.entPhysContainedIn, ),
        cmdgen.MibVariable(p.entPhysClass, ),
        cmdgen.MibVariable(p.entPhyParentRelPos, ),
        cmdgen.MibVariable(p.entPhysName, ),
        cmdgen.MibVariable(p.entPhysHwVer, ),
        cmdgen.MibVariable(p.entPhysFwVer, ),
        cmdgen.MibVariable(p.entPhysSwVer, ),
        cmdgen.MibVariable(p.entPhysSerialNum, ),
        cmdgen.MibVariable(p.entPhysMfgName, ),
        cmdgen.MibVariable(p.entPhysModelName, ),
        cmdgen.MibVariable(p.entPhysIsFRU, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) + ' querying physical table')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.entPhysDescr in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysDescr'] = current_val
            if v.entPhysContainedIn in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysContainedIn'] = int(current_val)
            if v.entPhysClass in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysClass'] = int(current_val)
            if v.entPhyParentRelPos in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhyParentRelPos'] = int(current_val)
            if v.entPhysName in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysName'] = current_val
            if v.entPhysHwVer in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysHwVer'] = current_val
            if v.entPhysFwVer in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysFwVer'] = current_val
            if v.entPhysSwVer in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysSwVer'] = current_val
            if v.entPhysSerialNum in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysSerialNum'] = current_val
            if v.entPhysMfgName in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysMfgName'] = current_val
            if v.entPhysModelName in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysModelName'] = current_val
            if v.entPhysIsFRU in current_oid:
                entity_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_physical_entities'][entity_oid][
                    'entPhysIsFRU'] = int(current_val)

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.entPhySensorType, ),
        cmdgen.MibVariable(p.entPhySensorScale, ),
        cmdgen.MibVariable(p.entPhySensorPrecision, ),
        cmdgen.MibVariable(p.entPhySensorValue, ),
        cmdgen.MibVariable(p.entPhySensorOperStatus, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) + ' querying physical table')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.entPhySensorType in current_oid:
                sensor_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_sensors'][sensor_oid][
                    'entPhySensorType'] = current_val
            if v.entPhySensorScale in current_oid:
                sensor_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_sensors'][sensor_oid]['entPhySensorScale'] = int(
                    current_val)
            if v.entPhySensorPrecision in current_oid:
                sensor_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_sensors'][sensor_oid][
                    'entPhySensorPrecision'] = current_val
            if v.entPhySensorValue in current_oid:
                sensor_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_sensors'][sensor_oid][
                    'entPhySensorValue'] = current_val
            if v.entPhySensorOperStatus in current_oid:
                sensor_oid = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_sensors'][sensor_oid][
                    'entPhySensorOperStatus'] = current_val

    interface_to_ipv4 = {}
    for ipv4_network in ipv4_networks:
        current_interface = ipv4_networks[ipv4_network]['interface']
        current_network = {
            'address': ipv4_networks[ipv4_network]['address'],
            'netmask': ipv4_networks[ipv4_network]['netmask']
        }
        if not current_interface in interface_to_ipv4:
            interface_to_ipv4[current_interface] = []
            interface_to_ipv4[current_interface].append(current_network)
        else:
            interface_to_ipv4[current_interface].append(current_network)

    for interface in interface_to_ipv4:
        results['snmp_interfaces'][int(
            interface)]['ipv4'] = interface_to_ipv4[interface]

    results['ansible_all_ipv4_addresses'] = all_ipv4_addresses

    if m_args['is_dell']:
        errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
            snmp_auth,
            cmdgen.UdpTransportTarget((m_args['host'], 161)),
            cmdgen.MibVariable(p.ChStackUnitCpuUtil5sec, ),
            lookupMib=False,
            lexicographicMode=False)

        if errorIndication:
            module.fail_json(msg=str(errorIndication) +
                             ' querying CPU busy indeces')

        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if current_oid == v.ChStackUnitCpuUtil5sec:
                results['ansible_ChStackUnitCpuUtil5sec'] = decode_type(
                    module, current_oid, val)

    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.lldpLocChassisIdSubtype, ),
        cmdgen.MibVariable(p.lldpLocChassisId, ),
        cmdgen.MibVariable(p.lldpLocSysName, ),
        cmdgen.MibVariable(p.lldpLocSysDesc, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) +
                         ' querying  lldp local system infomation.')

    for oid, val in varBinds:
        current_oid = oid.prettyPrint()
        current_val = val.prettyPrint()
        if current_oid == v.lldpLocChassisIdSubtype:
            results['snmp_lldp']['lldpLocChassisIdSubtype'] = current_val
        elif current_oid == v.lldpLocChassisId:
            results['snmp_lldp']['lldpLocChassisId'] = current_val
        elif current_oid == v.lldpLocSysName:
            results['snmp_lldp']['lldpLocSysName'] = current_val
        elif current_oid == v.lldpLocSysDesc:
            results['snmp_lldp']['lldpLocSysDesc'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.lldpLocPortIdSubtype, ),
        cmdgen.MibVariable(p.lldpLocPortId, ),
        cmdgen.MibVariable(p.lldpLocPortDesc, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) +
                         ' querying lldpLocPortTable counters')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.lldpLocPortIdSubtype in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'lldpLocPortIdSubtype'] = current_val
            if v.lldpLocPortId in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'lldpLocPortId'] = current_val
            if v.lldpLocPortDesc in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'lldpLocPortDesc'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.lldpLocManAddrLen, ),
        cmdgen.MibVariable(p.lldpLocManAddrIfSubtype, ),
        cmdgen.MibVariable(p.lldpLocManAddrIfId, ),
        cmdgen.MibVariable(p.lldpLocManAddrOID, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) +
                         ' querying lldpLocPortTable counters')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.lldpLocManAddrLen in current_oid:
                address = '.'.join(current_oid.split('.')[13:])
                results['snmp_lldp']['lldpLocManAddrLen'] = current_val
            if v.lldpLocManAddrIfSubtype in current_oid:
                address = '.'.join(current_oid.split('.')[13:])
                results['snmp_lldp']['lldpLocManAddrIfSubtype'] = current_val
            if v.lldpLocManAddrIfId in current_oid:
                address = '.'.join(current_oid.split('.')[13:])
                results['snmp_lldp']['lldpLocManAddrIfId'] = current_val
            if v.lldpLocManAddrOID in current_oid:
                address = '.'.join(current_oid.split('.')[13:])
                results['snmp_lldp']['lldpLocManAddrOID'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.lldpRemChassisIdSubtype, ),
        cmdgen.MibVariable(p.lldpRemChassisId, ),
        cmdgen.MibVariable(p.lldpRemPortIdSubtype, ),
        cmdgen.MibVariable(p.lldpRemPortId, ),
        cmdgen.MibVariable(p.lldpRemPortDesc, ),
        cmdgen.MibVariable(p.lldpRemSysName, ),
        cmdgen.MibVariable(p.lldpRemSysDesc, ),
        cmdgen.MibVariable(p.lldpRemSysCapSupported, ),
        cmdgen.MibVariable(p.lldpRemSysCapEnabled, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) +
                         ' querying lldpLocPortTable counters')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.lldpRemChassisIdSubtype in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemChassisIdSubtype'] = current_val
            if v.lldpRemChassisId in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemChassisId'] = current_val
            if v.lldpRemPortIdSubtype in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemPortIdSubtype'] = current_val
            if v.lldpRemPortId in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemPortId'] = current_val
            if v.lldpRemPortDesc in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemPortDesc'] = current_val
            if v.lldpRemSysName in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemSysName'] = current_val
            if v.lldpRemSysDesc in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemSysDesc'] = current_val
            if v.lldpRemSysCapSupported in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemSysCapSupported'] = current_val
            if v.lldpRemSysCapEnabled in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemSysCapEnabled'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.lldpRemManAddrIfSubtype, ),
        cmdgen.MibVariable(p.lldpRemManAddrIfId, ),
        cmdgen.MibVariable(p.lldpRemManAddrOID, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) +
                         ' querying lldpLocPortTable counters')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.lldpRemManAddrIfSubtype in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                address = '.'.join(current_oid.split('.')[16:])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemManAddrIfSubtype'] = current_val
            if v.lldpRemManAddrIfId in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                address = '.'.join(current_oid.split('.')[16:])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemManAddrIfId'] = current_val
            if v.lldpRemManAddrOID in current_oid:
                ifIndex = int(current_oid.split('.')[12])
                address = '.'.join(current_oid.split('.')[16:])
                results['snmp_interfaces'][ifIndex][
                    'lldpRemManAddrOID'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.cpfcIfRequests, ),
        cmdgen.MibVariable(p.cpfcIfIndications, ),
        cmdgen.MibVariable(p.requestsPerPriority, ),
        cmdgen.MibVariable(p.indicationsPerPriority, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) + ' querying PFC counters')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.cpfcIfRequests in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'cpfcIfRequests'] = current_val
            if v.cpfcIfIndications in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['snmp_interfaces'][ifIndex][
                    'cpfcIfIndications'] = current_val
            if v.requestsPerPriority in current_oid:
                ifIndex = int(current_oid.split('.')[-2])
                prio = int(current_oid.split('.')[-1])
                results['snmp_interfaces'][ifIndex]['requestsPerPriority'][
                    prio] = current_val
            if v.indicationsPerPriority in current_oid:
                ifIndex = int(current_oid.split('.')[-2])
                prio = int(current_oid.split('.')[-1])
                results['snmp_interfaces'][ifIndex]['indicationsPerPriority'][
                    prio] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.csqIfQosGroupStats, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) + ' querying QoS stats')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.csqIfQosGroupStats in current_oid:
                ifIndex = int(current_oid.split('.')[-4])
                ifDirection = int(current_oid.split('.')[-3])
                queueId = int(current_oid.split('.')[-2])
                counterId = int(current_oid.split('.')[-1])
                results['snmp_interfaces'][ifIndex]['queues'][ifDirection][
                    queueId][counterId] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.cefcFRUPowerOperStatus, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) + ' querying FRU')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.cefcFRUPowerOperStatus in current_oid:
                psuIndex = int(current_oid.split('.')[-1])
                results['snmp_psu'][psuIndex]['operstatus'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.ipCidrRouteEntry, ),
        cmdgen.MibVariable(p.ipCidrRouteStatus, ),
    )

    if errorIndication:
        module.fail_json(msg=str(errorIndication) + ' querying CidrRouteTable')

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.ipCidrRouteEntry in current_oid:
                # extract next hop ip from oid
                next_hop = current_oid.split(v.ipCidrRouteEntry + ".")[1]
                results['snmp_cidr_route'][next_hop][
                    'route_dest'] = current_val
            if v.ipCidrRouteStatus in current_oid:
                next_hop = current_oid.split(v.ipCidrRouteStatus + ".")[1]
                results['snmp_cidr_route'][next_hop]['status'] = current_val

    if not m_args['is_eos']:
        errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
            snmp_auth,
            cmdgen.UdpTransportTarget((m_args['host'], 161)),
            cmdgen.MibVariable(p.sysTotalMemery, ),
            cmdgen.MibVariable(p.sysTotalFreeMemery, ),
            cmdgen.MibVariable(p.sysTotalSharedMemory, ),
            cmdgen.MibVariable(p.sysTotalBuffMemory, ),
            cmdgen.MibVariable(p.sysCachedMemory, ),
            lookupMib=False,
            lexicographicMode=False)

        if errorIndication:
            module.fail_json(msg=str(errorIndication) +
                             ' querying system infomation.')

        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            if current_oid == v.sysTotalMemery:
                results['ansible_sysTotalMemery'] = decode_type(
                    module, current_oid, val)
            elif current_oid == v.sysTotalFreeMemery:
                results['ansible_sysTotalFreeMemery'] = decode_type(
                    module, current_oid, val)
            elif current_oid == v.sysTotalSharedMemory:
                results['ansible_sysTotalSharedMemory'] = decode_type(
                    module, current_oid, val)
            elif current_oid == v.sysTotalBuffMemory:
                results['ansible_sysTotalBuffMemory'] = decode_type(
                    module, current_oid, val)
            elif current_oid == v.sysCachedMemory:
                results['ansible_sysCachedMemory'] = decode_type(
                    module, current_oid, val)

        errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
            snmp_auth,
            cmdgen.UdpTransportTarget((m_args['host'], 161)),
            cmdgen.MibVariable(p.dot1qTpFdbEntry, ),
        )

        if errorIndication:
            module.fail_json(msg=str(errorIndication) + ' querying FdbTable')

        for varBinds in varTable:
            for oid, val in varBinds:
                current_oid = oid.prettyPrint()
                current_val = val.prettyPrint()
                if v.dot1qTpFdbEntry in current_oid:
                    # extract fdb info from oid
                    items = current_oid.split(v.dot1qTpFdbEntry +
                                              ".")[1].split(".")
                    # VLAN + MAC(6)
                    if len(items) != 7:
                        continue
                    mac_str = "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(
                        int(items[1]), int(items[2]), int(items[3]),
                        int(items[4]), int(items[5]), int(items[6]))
                    # key must be string
                    key = items[0] + '.' + mac_str
                    results['snmp_fdb'][key] = current_val

    module.exit_json(ansible_facts=results)
Ejemplo n.º 6
0
from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
    cmdgen.UsmUserData('usr-sha-aes128',
                       'authkey1',
                       'privkey1',
                       authProtocol=cmdgen.usmHMACSHAAuthProtocol,
                       privProtocol=cmdgen.usmAesCfb128Protocol),
    #cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)),
    cmdgen.UdpTransportTarget(('127.0.0.1', 161)),
    cmdgen.MibVariable('IF-MIB', '').loadMibs(),
    lexicographicMode=True,
    maxRows=100,
    ignoreNonIncreasingOid=True)

if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?'))
    else:
        for varBindTableRow in varBindTable:
            for name, val in varBindTableRow:
                print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
Ejemplo n.º 7
0
from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
    cmdgen.UsmUserData('usr-none-none'),
    cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)),
    #cmdgen.MibVariable('IP-MIB', 'ipAdEntAddr', '127.0.0.1'),
    cmdgen.MibVariable('IP-MIB', 'ipAdEntAddr', '192.168.1.9'),
    lookupNames=True,
    lookupValues=True)

# 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()))
    def getHostType(self, hostdic, typeoid, param=None):
        '''
        ' 获取指定主机的型号名称
        ' params:
        '     hostdic: 要获取型号的主机信息字典
        '     typeoid: 主机型号存储的MIB库节点
        ' return str: 主机型号名称
        ' raise ConfigException: 当获取不到主机型号时抛出
        '''
        errorIndication = None
        errorStatus = 0
        errorIndex = 0
        varBinds = None
        ipaddress = hostdic[HOST_CFG_KEY_IP]

        authProtocol = None
        privProtocol = None
        if 'SHA'.find(hostdic[HOST_CFG_KEY_AUTHPROTOCOL]) != -1:
            authProtocol = usmHMACSHAAuthProtocol
        else:
            authProtocol = usmHMACMD5AuthProtocol
        if 'AES'.find(str(hostdic[HOST_CFG_KEY_PRIVPROTOCOL])) != -1:
            privProtocol = usmAesCfb128Protocol
        else:
            privProtocol = usmDESPrivProtocol
        try:
            if 'v3' == hostdic[HOST_CFG_KEY_SNMPVERSION].lower():
                errorIndication, errorStatus, errorIndex, varBinds = \
                        cmdgen.CommandGenerator().getCmd(cmdgen.UsmUserData(\
                                                   hostdic[HOST_CFG_KEY_USER], \
                                                   hostdic[HOST_CFG_KEY_PASS], \
                                                   hostdic[HOST_CFG_KEY_PASS], \
                                                   authProtocol, \
                                                   privProtocol ), \
                                            cmdgen.UdpTransportTarget(\
                                                   (ipaddress, \
                                                    hostdic[HOST_CFG_KEY_PORT])), typeoid)
            else:
                errorIndication, errorStatus, errorIndex, varBinds = \
                        cmdgen.CommandGenerator().getCmd(
                                    cmdgen.CommunityData(hostdic[HOST_CFG_KEY_COMMUNITY]), \
                                    cmdgen.UdpTransportTarget(\
                                            (ipaddress, hostdic[HOST_CFG_KEY_PORT])), \
                                           typeoid)
            type = None
            if errorIndication is None \
                            and errorStatus == 0 \
                            and errorIndex == 0:
                if param == "enginid":

                    type = str(varBinds).split("'")[1]
                else:
                    for varoid, vartype in varBinds:
                        oid = str(varoid)
                        type = str(vartype)
                        if oid == typeoid and not type is None and type != '':
                            return type
                    # 不支持CH系列刀片
                    return None
                return type
            else:
                return None
        except Exception, error:
            logger.error("getHostType exception error info=%s" % (str(err)))
            return None
Ejemplo n.º 9
0
def snmpv3_getnext(ip='',
                   user='',
                   hash_meth=None,
                   hash_key=None,
                   cry_meth=None,
                   cry_key=None,
                   oid='',
                   num=1):
    # usmHMACMD5AuthProtocol - MD5 hashing
    # usmHMACSHAAuthProtocol - SHA hashing
    # usmNoAuthProtocol - no authentication
    # usmDESPrivProtocol - DES encryption
    # usm3DESEDEPrivProtocol - triple-DES encryption
    # usmAesCfb128Protocol - AES encryption, 128-bit
    # usmAesCfb192Protocol - AES encryption, 192-bit
    # usmAesCfb256Protocol - AES encryption, 256-bit
    # usmNoPrivProtocol - no encryption

    # ========================下面的操作在判断安全模型==========================
    # NoAuthNoPriv
    if hash_meth is None and cry_meth is None:
        hashval = cmdgen.usmNoAuthProtocol
        cryval = cmdgen.usmNoPrivProtocol
    # AuthNoPriv
    elif hash_meth is not None and cry_meth is None:
        if hash_meth == 'md5':
            hashval = cmdgen.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = cmdgen.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        cryval = cmdgen.usmNoPrivProtocol
    # AuthPriv
    elif hash_meth is not None and cry_meth is not None:
        if hash_meth == 'md5':
            hashval = cmdgen.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = cmdgen.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        if cry_meth == '3des':
            cryval = cmdgen.usm3DESEDEPrivProtocol
        elif cry_meth == 'des':
            cryval = cmdgen.usmDESPrivProtocol
        elif cry_meth == 'aes128':
            cryval = cmdgen.usmAesCfb128Protocol
        elif cry_meth == 'aes192':
            cryval = cmdgen.usmAesCfb192Protocol
        elif cry_meth == 'aes256':
            cryval = cmdgen.usmAesCfb256Protocol
        else:
            print('加密算法必须是3des, des, aes128, aes192 or aes256 !')
            return
    # 提供的参数不符合标准时给出提示
    else:
        print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。')
        return
    # ========================判断安全模型结束==========================
    errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
        cmdgen.UsmUserData(user,
                           hash_key,
                           cry_key,
                           authProtocol=hashval,
                           privProtocol=cryval),  # 添加用户,散列密钥,加密密钥,散列协议,加密协议
        cmdgen.UdpTransportTarget((ip, 161)),  # 添加目标地址和端口号
        oid,  # 指定oid
        lexicographicMode=True,
        maxRows=num,
        ignoreMonIncreasingOid=True  # 指定最大行数
    )

    if errorIndication:  # 打印错误
        print(errorIndication)
    else:
        if errorStatus:  # 打印错误
            print(
                '%s at %s' %
                (errorStatus.prettyPrint(),
                 errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?'))
        else:
            oid_list = []
            for varBindTableRow in varBindTable:
                for oid, val in varBindTableRow:
                    oid_list.append(
                        (oid.prettyPrint(),
                         val.prettyPrint()))  # 添加oid和对应值的信息到oid_list

    return oid_list  # 返回oid_list
Ejemplo n.º 10
0
def snmp_get_oid_v3(snmp_device,
                    snmp_user,
                    oid='.1.3.6.1.2.1.1.1.0',
                    auth_proto='sha',
                    encrypt_proto='aes128',
                    display_errors=True):
    '''
    Retrieve the given OID

    Default OID is MIB2, sysDescr

    snmp_device is a tuple = (hostname_or_IP, snmp_port)
    snmp_user is a tuple = (user_name, auth_key, encrypt_key)

    Defaults to SHA1-AES128 for authentication + encryption

    auth_proto can be 'sha' or 'md5' or 'none'
    encrypt_proto can be 'aes128', 'aes192', 'aes256', '3des', 'des', or 'none'


    From PySNMP manuals:  http://pysnmp.sourceforge.net/docs/current/security-configuration.html

    Optional authProtocol parameter may be used to specify non-default hash function algorithm.
    Possible values include:
    usmHMACMD5AuthProtocol -- MD5-based authentication protocol
    usmHMACSHAAuthProtocol -- SHA-based authentication protocol
    usmNoAuthProtocol -- no authentication to use (default)

    Optional privProtocol parameter may be used to specify non-default ciphering algorithm.
    Possible values include:
    usmDESPrivProtocol -- DES-based encryption protocol
    usmAesCfb128Protocol -- AES128-based encryption protocol (RFC3826)
    usm3DESEDEPrivProtocol -- triple DES-based encryption protocol (Extended Security Options)
    usmAesCfb192Protocol -- AES192-based encryption protocol (Extended Security Options)
    usmAesCfb256Protocol -- AES256-based encryption protocol (Extended Security Options)
    usmNoPrivProtocol -- no encryption to use (default)

    '''

    # unpack snmp_user
    a_user, auth_key, encrypt_key = snmp_user

    auth_proto_map = {
        'sha': cmdgen.usmHMACSHAAuthProtocol,
        'md5': cmdgen.usmHMACMD5AuthProtocol,
        'none': cmdgen.usmNoAuthProtocol
    }

    if auth_proto in auth_proto_map.keys():
        auth_protocol = auth_proto_map[auth_proto]
    else:
        raise ValueError("Invalid authentication protocol specified: %s" %
                         auth_proto)

    encrypt_proto_map = {
        'des': cmdgen.usmDESPrivProtocol,
        '3des': cmdgen.usm3DESEDEPrivProtocol,
        'aes128': cmdgen.usmAesCfb128Protocol,
        'aes192': cmdgen.usmAesCfb192Protocol,
        'aes256': cmdgen.usmAesCfb256Protocol,
        'none': cmdgen.usmNoPrivProtocol,
    }

    if encrypt_proto in encrypt_proto_map.keys():
        encrypt_protocol = encrypt_proto_map[encrypt_proto]
    else:
        raise ValueError("Invalid encryption protocol specified: %s" %
                         encrypt_proto)

    # Create a PYSNMP cmdgen object
    cmd_gen = cmdgen.CommandGenerator()

    (error_detected, error_status, error_index,
     snmp_data) = cmd_gen.getCmd(cmdgen.UsmUserData(
         a_user,
         auth_key,
         encrypt_key,
         authProtocol=auth_protocol,
         privProtocol=encrypt_protocol,
     ),
                                 cmdgen.UdpTransportTarget(snmp_device),
                                 oid,
                                 lookupNames=True,
                                 lookupValues=True)

    if not error_detected:
        return snmp_data
    else:
        if display_errors:
            print('ERROR DETECTED: ')
            print('    %-16s %-60s' % ('error_message', error_detected))
            print('    %-16s %-60s' % ('error_status', error_status))
            print('    %-16s %-60s' % ('error_index', error_index))
        return None
Ejemplo n.º 11
0
def snmpv3_getnext(ip='',
                   user='',
                   hash_meth=None,
                   hash_key=None,
                   cry_meth=None,
                   cry_key=None,
                   oid='',
                   num=1):
    #usmHMACMD5AuthProtocol - MD5 hashing
    #usmHMACSHAAuthProtocol - SHA hashing
    #usmNoAuthProtocol - no authentication
    #usmDESPrivProtocol - DES encryption
    #usm3DESEDEPrivProtocol - triple-DES encryption
    #usmAesCfb128Protocol - AES encryption, 128-bit
    #usmAesCfb192Protocol - AES encryption, 192-bit
    #usmAesCfb256Protocol - AES encryption, 256-bit
    #usmNoPrivProtocol - no encryption
    hashval = None
    cryval = None

    global vallist
    vallist = [None] * num
    #NoAuthNoPriv
    if hash_meth == None and cry_meth == None:
        hashval = cmdgen.usmNoAuthProtocol
        cryval = cmdgen.usmNoPrivProtocol
    #AuthNoPriv
    elif hash_meth != None and cry_meth == None:
        if hash_meth == 'md5':
            hashval = cmdgen.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = cmdgen.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        cryval = cmdgen.usmNoPrivProtocol
    #AuthPriv
    elif hash_meth != None and cry_meth != None:
        if hash_meth == 'md5':
            hashval = cmdgen.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = cmdgen.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        if cry_meth == '3des':
            cryval = cmdgen.usm3DESEDEPrivProtocol
        elif cry_meth == 'des':
            cryval = cmdgen.usmDESPrivProtocol
        elif cry_meth == 'aes128':
            cryval = cmdgen.usmAesCfb128Protocol
        elif cry_meth == 'aes192':
            cryval = cmdgen.usmAesCfb192Protocol
        elif cry_meth == 'aes256':
            cryval = cmdgen.usmAesCfb256Protocol
        else:
            print('加密算法必须是3des, des, aes128, aes192 or aes256 !')
            return
    #提供的参数不符合标准时给出提示
    else:
        print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。')
        return

    errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
        cmdgen.UsmUserData(user,
                           hash_key,
                           cry_key,
                           authProtocol=hashval,
                           privProtocol=cryval),
        cmdgen.UdpTransportTarget((ip, 161)),
        oid,
        lexicographicMode=True,
        maxRows=num,
        ignoreMonIncreasingOid=True)

    if errorIndication:
        print(errorIndication)
    else:
        if errorStatus:
            print(
                '%s at %s' %
                (errorStatus.prettyPrint(),
                 errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?'))
        else:
            oid_list = []
            for varBindTableRow in varBindTable:
                for oid, val in varBindTableRow:
                    o = StringIO()
                    print(oid, file=o)
                    oid_get = o.getvalue().strip()
                    o.close()
                    v = StringIO()
                    print(val, file=v)
                    val_get = v.getvalue().strip()
                    v.close()
                    oid_list.append((oid_get, val_get))

    return (oid_list)
Ejemplo n.º 12
0
    def _get(self, key):
        from pysnmp.entity.rfc3413.oneliner import cmdgen
        from pysnmp.error import PySnmpError
        from pysnmp.proto.rfc1905 import NoSuchInstance

        try:
            if self.interface.snmp_version == 2:
                errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator(
                ).getCmd(
                    cmdgen.CommunityData('exaddos',
                                         self.interface.snmp_password),
                    cmdgen.UdpTransportTarget((self.interface.router, 161)),
                    self.collection[key])
            elif self.interface.snmp_version == 3:
                from pysnmp.entity import config

                mapping_auth = {
                    'MD5': config.usmHMACMD5AuthProtocol,
                    'SHA': config.usmHMACSHAAuthProtocol,
                    '': config.usmNoAuthProtocol,
                }

                mapping_privacy = {
                    'DES': config.usmDESPrivProtocol,
                    '3DES': config.usm3DESEDEPrivProtocol,
                    'AES-128': config.usmAesCfb128Protocol,
                    'AES-192': config.usmAesCfb192Protocol,
                    'AES-256': config.usmAesCfb256Protocol,
                    '': config.usmNoPrivProtocol,
                }

                user = cmdgen.UsmUserData(
                    self.interface.snmp_user,
                    self.interface.snmp_auth_key,
                    self.interface.snmp_privacy_key,
                    authProtocol=mapping_auth[self.interface.snmp_auth_method],
                    privProtocol=mapping_privacy[
                        self.interface.snmp_privacy_method])

                transport = cmdgen.UdpTransportTarget(
                    (self.interface.router, 161))

                errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator(
                ).getCmd(user, transport, self.collection[key])


#					cmdgen.MibVariable('.'.join(str(_) for _ in self.collection[key]))
            else:
                raise NotImplemented(
                    'Feel free to add support for this SNMP version and send us the patch - thanks'
                )
        except PySnmpError:
            err('SNMP collection failed for %s %s' % (self.name, key))
            return None

        if (errorIndication, errorStatus, errorIndex) == (None, 0, 0):
            result = varBinds[0][1]

            if isinstance(result, NoSuchInstance):
                err('SNMP: %s did not have %s' % (self.name, key))
                sys.stderr.flush()
                return None

            try:
                return varBinds[0][1]
            except AttributeError:
                err('SNMP: %s did not have %s' % (self.name, key))
                return None
        else:
            err('SNMP collection failed for %s %s' % (self.name, key))
            return None
Ejemplo n.º 13
0
  cmdgen.MibVariable('SNMPv2-SMI', 'enterprises',42,36,0).addAsn1MibSource('./'),
  cmdgen.MibVariable('SNMPv2-SMI', 'enterprises',42,37,0).addAsn1MibSource('./'),
  cmdgen.MibVariable('SNMPv2-SMI', 'enterprises',42,38,0).addAsn1MibSource('./'),
  cmdgen.MibVariable('SNMPv2-SMI', 'enterprises',42,39,0).addAsn1MibSource('./'),
  cmdgen.MibVariable('SNMPv2-SMI', 'enterprises',42,40,0).addAsn1MibSource('./'),
  cmdgen.MibVariable('SNMPv2-SMI', 'enterprises',42,41,0).addAsn1MibSource('./'),
  cmdgen.MibVariable('SNMPv2-SMI', 'enterprises',42,42,0).addAsn1MibSource('./'),
  cmdgen.MibVariable('SNMPv2-SMI', 'enterprises',42,43,0).addAsn1MibSource('./'),)




# List of targets in the followin format:
# ( ( authData, transportTarget, varNames ), ... )

targets = (( cmdgen.UsmUserData('goldrush', authKey="authkey1", privKey="privkey1", authProtocol=cmdgen.usmHMACMD5AuthProtocol, privProtocol=cmdgen.usmDESPrivProtocol),
  cmdgen.UdpTransportTarget((addrList[i], 161)),smiSet ) for i in addrList)

# targets = (
#     # miner1 target (SNMPv3 over IPv4/UDP)
#     ( cmdgen.UsmUserData('goldrush', authKey="authkey1", privKey="privkey1", authProtocol=cmdgen.usmHMACMD5AuthProtocol, privProtocol=cmdgen.usmDESPrivProtocol),
#       cmdgen.UdpTransportTarget((mak1addr, 60001)),smiSet ),
#     #miner3
#     ( cmdgen.UsmUserData('goldrush', authKey="authkey1", privKey="privkey1", authProtocol=cmdgen.usmHMACMD5AuthProtocol, privProtocol=cmdgen.usmDESPrivProtocol),
#       cmdgen.UdpTransportTarget((mak1addr, 60003)),smiSet ),
#     #miner4
#     ( cmdgen.UsmUserData('goldrush', authKey="authkey1", privKey="privkey1", authProtocol=cmdgen.usmHMACMD5AuthProtocol, privProtocol=cmdgen.usmDESPrivProtocol),
#       cmdgen.UdpTransportTarget((mak1addr, 60004)),smiSet ),
#      #miner5
#     ( cmdgen.UsmUserData('goldrush', authKey="authkey1", privKey="privkey1", authProtocol=cmdgen.usmHMACMD5AuthProtocol, privProtocol=cmdgen.usmDESPrivProtocol),
#         cmdgen.UdpTransportTarget((mak1addr, 60005)),smiSet ),
Ejemplo n.º 14
0
  row=row+1

  column = device.split()
  sheet.write(row, 0,column[0] )
  sheet.write(row, 1,column[1] )
  
  print column[0]

  

  
  
  varBinds = cmdGen.nextCmd(cmdgen.CommunityData('g0al1e'),cmdgen.UdpTransportTarget((column[1], 161)),'1.3.6.1.2.1.14.10.1.6')
  #print  varBinds[3]
  if not varBinds[3]:
    varBinds = cmdGen.nextCmd(cmdgen.UsmUserData('scbcnim','scb#m0nit@r$'),cmdgen.UdpTransportTarget((column[1], 161)),'1.3.6.1.2.1.14.10.1.6')
    for list in varBinds[3]:
      for y in list:
        regex1=str(y).replace('(ObjectName(\'1.3.6.1.2.1.14.10.1.6.', '')
        regex2=str(regex1).replace('.0\')','')
        x=str(regex2).replace(')','').replace('(','')
        neighbor=x.split(',')[0]
        state=x.split(',')[1]
        if state==" Integer8":
           state="UP"
        else:
           state="DOWN"
      
      
        print "Neighbor: "+neighbor
        sheet.write(row,2,neighbor)
Ejemplo n.º 15
0
# GETNEXT Command Generator
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto import rfc1902

# ( ( authData, transportTarget, varNames ), ... )
targets = (
    # 1-st target (SNMPv1 over IPv4/UDP)
    (cmdgen.CommunityData('public', mpModel=0),
     cmdgen.UdpTransportTarget(
         ('localhost', 161)), ((1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 3, 1))),
    # 2-nd target (SNMPv2c over IPv4/UDP)
    (cmdgen.CommunityData('public'),
     cmdgen.UdpTransportTarget(('localhost', 161)), ((1, 3, 6, 1, 4, 1), )),
    # 3-nd target (SNMPv3 over IPv4/UDP)
    (cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
     cmdgen.UdpTransportTarget(('localhost', 161)), ((1, 3, 6, 1, 5, 1), )),
    # 4-th target (SNMPv3 over IPv6/UDP)
    (cmdgen.UsmUserData('usr-md5-none',
                        'authkey1'), cmdgen.Udp6TransportTarget(
                            ('::1', 161)), ((1, 3, 6, 1, 6, 1), )),
    # 5-th target (SNMPv2c over Local Domain Socket)
    (cmdgen.CommunityData('public'),
     cmdgen.UnixTransportTarget('/tmp/snmp-agent'), ((1, 3, 6, 1, 6, 1), ))
    # N-th target
    # ...
)


def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBindTable, cbCtx):
    (varBindHead, authData, transportTarget) = cbCtx
Ejemplo n.º 16
0
# SET Command Generator with MIB resolution
import string
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.entity.rfc3413 import mibvar

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd(
    # SNMP v1
    #    cmdgen.CommunityData('test-agent', 'public', 0),
    # SNMP v2
    #    cmdgen.CommunityData('test-agent', 'public'),
    # SNMP v3
    cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'),
    # Transport
    cmdgen.UdpTransportTarget(('localhost', 161)),
    # Request variable(s)
    ((('SNMPv2-MIB', 'sysDescr'), 0), 'new name'))

if errorIndication:
    print errorIndication
else:
    if errorStatus:
        print '%s at %s\n' % (errorStatus.prettyPrint(),
                              varBinds[int(errorIndex) - 1])
    else:
        for oid, val in varBinds:
            (symName,
             modName), indices = mibvar.oidToMibName(cmdGen.mibViewController,
                                                     oid)
            val = mibvar.cloneFromMibValue(cmdGen.mibViewController, modName,
Ejemplo n.º 17
0
    def validate_connectivity(alert_source):
        # Fill optional parameters with default values if not set in input
        if not alert_source.get('port'):
            alert_source['port'] = constants.DEFAULT_SNMP_CONNECT_PORT

        if not alert_source.get('context_name'):
            alert_source['context_name'] = None

        if not alert_source.get('retry_num'):
            alert_source['retry_num'] = constants.DEFAULT_SNMP_RETRY_NUM

        if not alert_source.get('expiration'):
            alert_source['expiration'] = constants.DEFAULT_SNMP_EXPIRATION_TIME

        if CONF.snmp_validation_enabled is False:
            return alert_source

        cmd_gen = cmdgen.CommandGenerator()

        # Register engine observer to get engineId,
        # Code reference from: http://snmplabs.com/pysnmp/
        observer_context = {}
        cmd_gen.snmpEngine.observer.registerObserver(
            lambda e, p, v, c: c.update(
                securityEngineId=v['securityEngineId']),
            'rfc3412.prepareDataElements:internal',
            cbCtx=observer_context
        )

        version = alert_source.get('version')

        # Connect to alert source through snmp get to check the configuration
        try:
            if version.lower() == 'snmpv3':
                auth_key = cryptor.decode(alert_source['auth_key'])
                privacy_key = cryptor.decode(alert_source['privacy_key'])
                auth_protocol = None
                privacy_protocol = None
                if alert_source['auth_protocol']:
                    auth_protocol = constants.AUTH_PROTOCOL_MAP.get(
                        alert_source['auth_protocol'].lower())
                if alert_source['privacy_protocol']:
                    privacy_protocol = constants.PRIVACY_PROTOCOL_MAP.get(
                        alert_source['privacy_protocol'].lower())

                engine_id = alert_source.get('engine_id')
                if engine_id:
                    engine_id = OctetString.fromHexString(engine_id)
                error_indication, __, __, __ = cmd_gen.getCmd(
                    cmdgen.UsmUserData(alert_source['username'],
                                       authKey=auth_key,
                                       privKey=privacy_key,
                                       authProtocol=auth_protocol,
                                       privProtocol=privacy_protocol,
                                       securityEngineId=engine_id),
                    cmdgen.UdpTransportTarget((alert_source['host'],
                                               alert_source['port']),
                                              timeout=alert_source[
                                                  'expiration'],
                                              retries=alert_source[
                                                  'retry_num']),
                    constants.SNMP_QUERY_OID,
                )

                if 'securityEngineId' in observer_context:
                    engine_id = observer_context.get('securityEngineId')
                    alert_source['engine_id'] = binascii.hexlify(
                        engine_id.asOctets()).decode()
            else:
                community_string = cryptor.decode(
                    alert_source['community_string'])
                error_indication, __, __, __ = cmd_gen.getCmd(
                    cmdgen.CommunityData(
                        community_string,
                        contextName=alert_source['context_name']),
                    cmdgen.UdpTransportTarget((alert_source['host'],
                                               alert_source['port']),
                                              timeout=alert_source[
                                                  'expiration'],
                                              retries=alert_source[
                                                  'retry_num']),
                    constants.SNMP_QUERY_OID,
                )

            if not error_indication:
                return alert_source

            # Prepare exception with error_indication
            msg = six.text_type(error_indication)
        except Exception as e:
            msg = six.text_type(e)

        # Since validation occur error, raise exception
        LOG.error("Configuration validation failed with alert source for "
                  "reason: %s." % msg)
        raise exception.SNMPConnectionFailed(msg)
Ejemplo n.º 18
0
def main():
    module = AnsibleModule(argument_spec=dict(
        host=dict(required=True),
        version=dict(required=True, choices=['v2', 'v2c', 'v3']),
        community=dict(required=False, default=False),
        username=dict(required=False),
        level=dict(required=False, choices=['authNoPriv', 'authPriv']),
        integrity=dict(required=False, choices=['md5', 'sha']),
        privacy=dict(required=False, choices=['des', 'aes']),
        authkey=dict(required=False),
        privkey=dict(required=False),
        removeplaceholder=dict(required=False)),
                           required_together=(
                               ['username', 'level', 'integrity', 'authkey'],
                               ['privacy', 'privkey'],
                           ),
                           supports_check_mode=False)

    m_args = module.params

    if not has_pysnmp:
        module.fail_json(msg='Missing required pysnmp module (check docs)')

    cmdGen = cmdgen.CommandGenerator()

    # Verify that we receive a community when using snmp v2
    if m_args['version'] == "v2" or m_args['version'] == "v2c":
        if m_args['community'] == False:
            module.fail_json(msg='Community not set when using snmp version 2')

    if m_args['version'] == "v3":
        if m_args['username'] == None:
            module.fail_json(msg='Username not set when using snmp version 3')

        if m_args['level'] == "authPriv" and m_args['privacy'] == None:
            module.fail_json(
                msg='Privacy algorithm not set when using authPriv')

        if m_args['integrity'] == "sha":
            integrity_proto = cmdgen.usmHMACSHAAuthProtocol
        elif m_args['integrity'] == "md5":
            integrity_proto = cmdgen.usmHMACMD5AuthProtocol

        if m_args['privacy'] == "aes":
            privacy_proto = cmdgen.usmAesCfb128Protocol
        elif m_args['privacy'] == "des":
            privacy_proto = cmdgen.usmDESPrivProtocol

    # Use SNMP Version 2
    if m_args['version'] == "v2" or m_args['version'] == "v2c":
        snmp_auth = cmdgen.CommunityData(m_args['community'])

    # Use SNMP Version 3 with authNoPriv
    elif m_args['level'] == "authNoPriv":
        snmp_auth = cmdgen.UsmUserData(m_args['username'],
                                       authKey=m_args['authkey'],
                                       authProtocol=integrity_proto)

    # Use SNMP Version 3 with authPriv
    else:
        snmp_auth = cmdgen.UsmUserData(m_args['username'],
                                       authKey=m_args['authkey'],
                                       privKey=m_args['privkey'],
                                       authProtocol=integrity_proto,
                                       privProtocol=privacy_proto)

    # Use p to prefix OIDs with a dot for polling
    p = DefineOid(dotprefix=True)
    # Use v without a prefix to use with return values
    v = DefineOid(dotprefix=False)

    Tree = lambda: defaultdict(Tree)

    results = Tree()

    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.sysDescr, ),
        cmdgen.MibVariable(p.sysObjectId, ),
        cmdgen.MibVariable(p.sysUpTime, ),
        cmdgen.MibVariable(p.sysContact, ),
        cmdgen.MibVariable(p.sysName, ),
        cmdgen.MibVariable(p.sysLocation, ),
        lookupMib=False)

    if errorIndication:
        module.fail_json(msg=str(errorIndication))

    for oid, val in varBinds:
        current_oid = oid.prettyPrint()
        current_val = val.prettyPrint()
        if current_oid == v.sysDescr:
            results['ansible_sysdescr'] = decode_hex(current_val)
        elif current_oid == v.sysObjectId:
            results['ansible_sysobjectid'] = current_val
        elif current_oid == v.sysUpTime:
            results['ansible_sysuptime'] = current_val
        elif current_oid == v.sysContact:
            results['ansible_syscontact'] = current_val
        elif current_oid == v.sysName:
            results['ansible_sysname'] = current_val
        elif current_oid == v.sysLocation:
            results['ansible_syslocation'] = current_val

    errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((m_args['host'], 161)),
        cmdgen.MibVariable(p.ifIndex, ),
        cmdgen.MibVariable(p.ifDescr, ),
        cmdgen.MibVariable(p.ifMtu, ),
        cmdgen.MibVariable(p.ifSpeed, ),
        cmdgen.MibVariable(p.ifPhysAddress, ),
        cmdgen.MibVariable(p.ifAdminStatus, ),
        cmdgen.MibVariable(p.ifOperStatus, ),
        cmdgen.MibVariable(p.ipAdEntAddr, ),
        cmdgen.MibVariable(p.ipAdEntIfIndex, ),
        cmdgen.MibVariable(p.ipAdEntNetMask, ),
        cmdgen.MibVariable(p.ifAlias, ),
        lookupMib=False)

    if errorIndication:
        module.fail_json(msg=str(errorIndication))

    interface_indexes = []

    all_ipv4_addresses = []
    ipv4_networks = Tree()

    for varBinds in varTable:
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if v.ifIndex in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['ansible_interfaces'][ifIndex]['ifindex'] = current_val
                interface_indexes.append(ifIndex)
            if v.ifDescr in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['ansible_interfaces'][ifIndex]['name'] = current_val
            if v.ifMtu in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['ansible_interfaces'][ifIndex]['mtu'] = current_val
            if v.ifMtu in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['ansible_interfaces'][ifIndex]['speed'] = current_val
            if v.ifPhysAddress in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['ansible_interfaces'][ifIndex]['mac'] = decode_mac(
                    current_val)
            if v.ifAdminStatus in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['ansible_interfaces'][ifIndex][
                    'adminstatus'] = lookup_adminstatus(int(current_val))
            if v.ifOperStatus in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['ansible_interfaces'][ifIndex][
                    'operstatus'] = lookup_operstatus(int(current_val))
            if v.ipAdEntAddr in current_oid:
                curIPList = current_oid.rsplit('.', 4)[-4:]
                curIP = ".".join(curIPList)
                ipv4_networks[curIP]['address'] = current_val
                all_ipv4_addresses.append(current_val)
            if v.ipAdEntIfIndex in current_oid:
                curIPList = current_oid.rsplit('.', 4)[-4:]
                curIP = ".".join(curIPList)
                ipv4_networks[curIP]['interface'] = current_val
            if v.ipAdEntNetMask in current_oid:
                curIPList = current_oid.rsplit('.', 4)[-4:]
                curIP = ".".join(curIPList)
                ipv4_networks[curIP]['netmask'] = current_val

            if v.ifAlias in current_oid:
                ifIndex = int(current_oid.rsplit('.', 1)[-1])
                results['ansible_interfaces'][ifIndex][
                    'description'] = current_val

    interface_to_ipv4 = {}
    for ipv4_network in ipv4_networks:
        current_interface = ipv4_networks[ipv4_network]['interface']
        current_network = {
            'address': ipv4_networks[ipv4_network]['address'],
            'netmask': ipv4_networks[ipv4_network]['netmask']
        }
        if not current_interface in interface_to_ipv4:
            interface_to_ipv4[current_interface] = []
            interface_to_ipv4[current_interface].append(current_network)
        else:
            interface_to_ipv4[current_interface].append(current_network)

    for interface in interface_to_ipv4:
        results['ansible_interfaces'][int(
            interface)]['ipv4'] = interface_to_ipv4[interface]

    results['ansible_all_ipv4_addresses'] = all_ipv4_addresses

    module.exit_json(ansible_facts=results)
Ejemplo n.º 19
0
    def open_snmp_v3_connection(self, host, user, password='',
                                encryption_password=None,
                                authentication_protocol=None,
                                encryption_protocol=None, port=161,
                                timeout=1.0, retries=5, alias=None):
        """Opens a new SNMP v3 Connection to the given host.

        If no `port` is given, the default port 161 is used.

        Valid values for `authentication_protocol` are `MD5`, `SHA`, and None.
        Valid values for `encryption_protocol` are `DES`,`3DES`, `AES128`,
        `AES192`, `AES256` and None.

        The optional `alias` is a name for the connection and it can be used
        for switching between connections, similarly as the index. See `Switch
        Connection` for more details about that.
        """

        host = str(host)
        port = int(port)
        user = str(user)
        timeout = float(timeout)
        retries = int(retries)

        if password is not None:
            password = str(password)

        if encryption_password is not None:
            encryption_password = str(encryption_password)

        if alias:
            alias = str(alias)

        if authentication_protocol is not None:
            authentication_protocol = authentication_protocol.upper()

        try:
            authentication_protocol = {
                None: cmdgen.usmNoAuthProtocol,
                'MD5': cmdgen.usmHMACMD5AuthProtocol,
                'SHA': cmdgen.usmHMACSHAAuthProtocol
            }[authentication_protocol]
        except KeyError:
            raise RuntimeError('Invalid authentication protocol %s' %
                               authentication_protocol)

        if encryption_protocol is not None:
            encryption_protocol = encryption_protocol.upper()

        try:
            encryption_protocol = {
                None: cmdgen.usmNoPrivProtocol,
                'DES': cmdgen.usmDESPrivProtocol,
                '3DES': cmdgen.usm3DESEDEPrivProtocol,
                'AES128': cmdgen.usmAesCfb128Protocol,
                'AES192': cmdgen.usmAesCfb192Protocol,
                'AES256': cmdgen.usmAesCfb256Protocol,
            }[encryption_protocol]
        except KeyError:
            raise RuntimeError('Invalid encryption protocol %s' %
                               encryption_protocol)

        authentication_data = cmdgen.UsmUserData(
                                    user,
                                    password,
                                    encryption_password,
                                    authentication_protocol,
                                    encryption_protocol)

        transport_target = cmdgen.UdpTransportTarget(
                                        (host, port), timeout, retries)

        conn = _SnmpConnection(authentication_data, transport_target)
        self._active_connection = conn

        return self._cache.register(self._active_connection, alias)