from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen1 = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBinds = cmdGen1.getCmd(
    cmdgen.CommunityData('public'),
    cmdgen.UdpTransportTarget(('192.168.1.11', 161)),
    cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr'),
    lookupNames=True,
    lookupValues=True)

if errorIndication:
    print errorIndication
else:
    for name, val in varBinds:
        print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
Example #2
0
# -*- coding: utf-8 -*-
Example #3
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
Example #4
0
File: comeon.py Project: hc990/let
# -*- coding: utf-8 -*-
Example #5
0
def snmp_get(ip):
    nbridlist = []
    nbriplist = []
    ospf_devices = {}

    #Creating command generator object
    cmdGen = cmdgen.CommandGenerator()

    #Performing SNMP GETNEXT operations on the OSPF OIDs
    #The basic syntax of nextCmd: nextCmd(authData, transportTarget, *varNames)
    #The nextCmd method returns a tuple of (errorIndication, errorStatus, errorIndex, varBindTable)

    errorIndication, errorStatus, errorIndex, varBindNbrTable = cmdGen.nextCmd(
        cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)),
        '1.3.6.1.2.1.14.10.1.3')

    #print cmdGen.nextCmd(cmdgen.CommunityData(comm),cmdgen.UdpTransportTarget((ip, 161)),'1.3.6.1.2.1.14.10.1.3')
    #print varBindNbrTable

    errorIndication, errorStatus, errorIndex, varBindNbrIpTable = cmdGen.nextCmd(
        cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)),
        '1.3.6.1.2.1.14.10.1.1')

    #print varBindNbrIpTable

    errorIndication, errorStatus, errorIndex, varBindHostTable = cmdGen.nextCmd(
        cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)),
        '1.3.6.1.4.1.9.2.1.3')

    #print varBindHostTable

    errorIndication, errorStatus, errorIndex, varBindHostIdTable = cmdGen.nextCmd(
        cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)),
        '1.3.6.1.2.1.14.1.1')

    #print varBindHostIdTable

    #Extract and print out the results
    for varBindNbrTableRow in varBindNbrTable:
        for oid, nbrid in varBindNbrTableRow:
            hex_string = binascii.hexlify(str(nbrid))
            #print hex_string
            octets = [
                hex_string[i:i + 2] for i in range(0, len(hex_string), 2)
            ]
            #print octets
            ip = [int(i, 16) for i in octets]
            #print ip
            nbr_r_id = '.'.join(str(i) for i in ip)
            #print nbr_r_id
            nbridlist.append(nbr_r_id)
            #print('%s = %s' % (oid, nbr_r_id))

    for varBindNbrIpTableRow in varBindNbrIpTable:
        for oid, nbrip in varBindNbrIpTableRow:
            hex_string = binascii.hexlify(str(nbrip))
            octets = [
                hex_string[i:i + 2] for i in range(0, len(hex_string), 2)
            ]
            ip = [int(i, 16) for i in octets]
            nbr_ip = '.'.join(str(i) for i in ip)
            nbriplist.append(nbr_ip)
            #print('%s = %s' % (oid, nbr_ip))

    for varBindHostTableRow in varBindHostTable:
        for oid, host in varBindHostTableRow:
            ospf_host = str(host)
            #print('%s = %s' % (oid, host))

    for varBindHostIdTableRow in varBindHostIdTable:
        for oid, hostid in varBindHostIdTableRow:
            hex_string = binascii.hexlify(str(hostid))
            octets = [
                hex_string[i:i + 2] for i in range(0, len(hex_string), 2)
            ]
            ip = [int(i, 16) for i in octets]
            ospf_host_id = '.'.join(str(i) for i in ip)
            #print('%s = %s' % (oid, hostid))

    #Adding OSPF data by device in the ospf_device dictionary
    ospf_devices["Host"] = ospf_host
    ospf_devices["HostId"] = ospf_host_id
    ospf_devices["NbrRtrId"] = nbridlist
    ospf_devices["NbrRtrIp"] = nbriplist

    ospf.append(ospf_devices)

    return ospf
Example #6
0
args = parser.parse_args()

# Provide information about requirements
print('You may need to check the following in the printer\'s configuration:')
print('  - SNMP service is enabled (for fetching model and versions)')
print('  - FTP service is enabled (for uploading firmware)')
print('  - an administrator password is set (for connecting to FTP)')
input('Press Ctrl-C to exit or Enter to continue...')

# Get SNMP data
print('Getting SNMP data from printer at %s...' % args.ip)
sys.stdout.flush()

cg = cmdgen.CommandGenerator()
error, status, index, table = cg.nextCmd(
    cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget((args.ip, 161)),
    '1.3.6.1.4.1.2435.2.4.3.99.3.1.6.1.2')

print('done')

if error: raise error
if status:
    raise 'ERROR: %s at %s' % (status.prettyPrint(),
                               index and table[-1][int(index) - 1] or '?')

# Process SNMP data
serial = None
model = None
spec = None
firmId = None
firmInfo = []
#
# Send SNMP GETNEXT requests using the following options:
#
# * with SNMPv2c, community 'public'
# * over IPv4/UDP
# * to an Agent at demo.snmplabs.com:161
# * for two OIDs in string form
# * stop when response OIDs leave the scopes of initial OIDs
#
from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
    cmdgen.CommunityData('public'),
    cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)),
    '1.3.6.1.2.1.2.2.1.2',
    '1.3.6.1.2.1.2.2.1.3',
)

if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?'
            )
        )
    else:
        for varBindTableRow in varBindTable:
Example #8
0
    def __init__(self,
                 host,
                 community="public",
                 version=2,
                 secname=None,
                 authprotocol=None,
                 authpassword=None,
                 privprotocol=None,
                 privpassword=None,
                 bulk=40,
                 none=False):
        """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
        :param bulk: Max repetition value for `GETBULK` requests. Set
            to `0` to disable.
        :type bulk: int
        :param none: When enabled, will return None for not found
            values (instead of raising an exception)
        :type none: bool
        """
        self._host = host
        self._version = version
        self._none = none
        if version == 3:
            self._cmdgen = cmdgen.CommandGenerator()
        else:
            if not hasattr(self._tls, "cmdgen"):
                self._tls.cmdgen = cmdgen.CommandGenerator()
            self._cmdgen = self._tls.cmdgen
        if version == 1 and none:
            raise ValueError("None-GET requests not compatible with SNMPv1")

        # 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
        mo = re.match(
            r'^(?:'
            r'\[(?P<ipv6>[\d:A-Fa-f]+)\]|'
            r'(?P<ipv4>[\d\.]+)|'
            r'(?P<any>.*?))'
            r'(?::(?P<port>\d+))?$', host)
        if mo.group("port"):
            port = int(mo.group("port"))
        else:
            port = 161
        if mo.group("ipv6"):
            self._transport = cmdgen.Udp6TransportTarget(
                (mo.group("ipv6"), port))
        elif mo.group("ipv4"):
            self._transport = cmdgen.UdpTransportTarget(
                (mo.group("ipv4"), port))
        else:
            results = socket.getaddrinfo(mo.group("any"), port, 0,
                                         socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            # We should try to connect to each result to determine if
            # the given family is available. However, we cannot do
            # that over UDP. Let's implement a safe choice. If we have
            # an IPv4 address, use that. If not, use IPv6. If we want
            # to add an option to force IPv6, it is a good place.
            if [x for x in results if x[0] == socket.AF_INET]:
                self._transport = cmdgen.UdpTransportTarget(
                    (mo.group("any"), port))
            else:
                self._transport = cmdgen.Udp6TransportTarget(
                    (mo.group("any"), port))

        # Bulk stuff
        self.bulk = bulk
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)')

    cmd_gen = cmdgen.CommandGenerator()

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

    if m_args['version'] == "v3":
        if m_args['username'] is 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()

    host = m_args['host']

    error_indication, error_status, error_index, var_binds = cmd_gen.nextCmd(
        snmp_auth, cmdgen.UdpTransportTarget((host, 161)),
        cmdgen.MibVariable(p.if_descr, ))

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

    (if_table, inverse_if_table) = get_iftable(var_binds)

    error_indication, error_status, error_index, var_table = cmd_gen.nextCmd(
        snmp_auth,
        cmdgen.UdpTransportTarget((host, 161)),
        cmdgen.MibVariable(p.lldp_rem_port_id, ),
        cmdgen.MibVariable(p.lldp_rem_port_desc, ),
        cmdgen.MibVariable(p.lldp_rem_sys_desc, ),
        cmdgen.MibVariable(p.lldp_rem_sys_name, ),
        cmdgen.MibVariable(p.lldp_rem_chassis_id, ),
    )

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

    lldp_rem_sys = dict()
    lldp_rem_port_id = dict()
    lldp_rem_port_desc = dict()
    lldp_rem_chassis_id = dict()
    lldp_rem_sys_desc = dict()

    vbd = []

    for var_binds in var_table:
        for oid, val in var_binds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            vbd.append(current_oid)
            vbd.append(current_val)

            try:
                if_name = inverse_if_table[str(current_oid.split(".")[-2])]
            except Exception as e:
                print json.dumps({
                    "unbound_interface_index":
                    str(current_oid.split(".")[-2])
                })
                module.fail_json(msg="unboundinterface in inverse if table")

            if v.lldp_rem_sys_name in current_oid:
                lldp_rem_sys[if_name] = current_val
                continue
            if v.lldp_rem_port_id in current_oid:
                lldp_rem_port_id[if_name] = current_val
                continue
            if v.lldp_rem_port_desc in current_oid:
                lldp_rem_port_desc[if_name] = current_val
                continue
            if v.lldp_rem_chassis_id in current_oid:
                lldp_rem_chassis_id[if_name] = current_val
                continue
            if v.lldp_rem_sys_desc in current_oid:
                lldp_rem_sys_desc[if_name] = current_val
                continue

    lldp_data = dict()

    for intf in lldp_rem_sys.viewkeys():
        lldp_data[intf] = {
            'neighbor_sys_name': lldp_rem_sys[intf],
            'neighbor_port_desc': lldp_rem_port_desc[intf],
            'neighbor_port_id': lldp_rem_port_id[intf],
            'neighbor_sys_desc': lldp_rem_sys_desc[intf],
            'neighbor_chassis_id': lldp_rem_chassis_id[intf]
        }

    results['ansible_lldp_facts'] = lldp_data
    module.exit_json(ansible_facts=results)
Example #10
0
parser.add_argument('--use-collectd',
                    help='Send stats to Collectd',
                    action='store_true',
                    default=False)

args = parser.parse_args()
# Namespace(graphite_host='127.0.0.1', graphite_port=2013, host='pdu-eth1', snmp_community='dog33show', snmp_port=161, use_collectd=False, use_graphite=False)

# rPDUIdentDeviceNumOutlets = 1.3.6.1.4.1.318.1.1.12.1.8
# rPDUOutletStatusOutletName = 1.3.6.1.4.1.318.1.1.12.3.5.1.1.2
value = (1, 3, 6, 1, 4, 1, 318, 1, 1, 12, 3, 5, 1, 1, 2)

generator = cmdgen.CommandGenerator()
comm_data = cmdgen.CommunityData('server', args.snmp_community,
                                 1)  # 1 means version SNMP v2c
transport = cmdgen.UdpTransportTarget((args.host, args.snmp_port))

real_fun = getattr(generator, 'nextCmd')
res = (errorIndication, errorStatus, errorIndex, varBinds)\
    = real_fun(comm_data, transport, value)

if not errorIndication is None or errorStatus is True:
    print "Error: %s %s %s %s" % res
    sys.exit(1)

a = []
# TODO Get number of outlets via SNMP
for i in range(0, 23):
    a.append(varBinds[i][0][1])

# rPDU Outlet AMP (not documented) = .1.3.6.1.4.1.318.1.1.12.3.5.1.1.7
#!/usr/bin/env/python3

from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

system_up_time_oid = "1.3.6.1.2.1.1.3.0"
cisco_contact_info_oid = "1.3.6.1.4.1.9.2.1.61.0"

errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
    cmdgen.CommunityData('secret'),
    cmdgen.UdpTransportTarget(('172.16.1.189', 161)), system_up_time_oid,
    cisco_contact_info_oid)

# 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(), str(val)))
Example #12
0
    def table(self,
              oid,
              columns=None,
              column_value_mapping=None,
              non_repeaters=0,
              max_repetitions=20,
              fetch_all_columns=True):
        """
        Get a table of values with the given OID prefix.
        """
        snmpsecurity = self._get_snmp_security()
        base_oid = oid.strip(".")

        if not fetch_all_columns and not columns:
            raise ValueError("please use the columns argument to "
                             "indicate which columns to fetch")

        if fetch_all_columns:
            columns_to_fetch = [""]
        else:
            columns_to_fetch = ["." + str(col_id) for col_id in columns.keys()]

        full_obj_table = []

        for col in columns_to_fetch:
            try:
                engine_error, pdu_error, pdu_error_index, obj_table = self._cmdgen.bulkCmd(
                    snmpsecurity,
                    cmdgen.UdpTransportTarget((self.host, self.port),
                                              timeout=self.timeout,
                                              retries=self.retries),
                    non_repeaters,
                    max_repetitions,
                    oid + col,
                )

            except Exception as e:
                raise SNMPError(e)
            if engine_error:
                raise SNMPError(engine_error)
            if pdu_error:
                raise SNMPError(pdu_error.prettyPrint())

            # remove any trailing rows from the next subtree
            try:
                while not obj_table[-1][0][0].prettyPrint().lstrip(
                        ".").startswith(base_oid + col + "."):
                    obj_table.pop()
            except IndexError:
                pass

            # append this column to full result
            full_obj_table += obj_table

        t = Table(columns=columns, column_value_mapping=column_value_mapping)

        for row in full_obj_table:
            for name, value in row:
                oid = name.prettyPrint().strip(".")
                value = _convert_value_to_native(value)
                column, row_id = oid[len(base_oid) + 1:].split(".", 1)
                t._add_value(int(column), row_id, value)

        return t
Example #13
0
    def getRemoteSwitchDataFromSnmpVersion2C(self):

        # init value
        count = 0
        cmdGen = None
        dictRemoteSwitchDataFromPort = {}

        try:
            # create object for create snmp command
            cmdGen = cmdgen.CommandGenerator()
        except Exception as err:
            print(" Switch ip " + self.switchIp +
                  " 226 terminate because handling run-time error : " +
                  str(err))
            sys.exit()

        try:
            # <snmpv2c>
            errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
                cmdgen.CommunityData('public'),
                cmdgen.UdpTransportTarget(
                    (self.switchIp, 161)), '1.0.8802.1.1.2.1.4.1.1.5',
                '1.0.8802.1.1.2.1.4.1.1.7', '1.0.8802.1.1.2.1.4.1.1.8',
                '1.0.8802.1.1.2.1.4.1.1.4', '1.0.8802.1.1.2.1.4.1.1.6')

            if errorIndication:
                print(errorIndication)
                count += 1
            else:
                if errorStatus:
                    print('%s at %s' %
                          (errorStatus.prettyPrint(), errorIndex
                           and varBindTable[-1][int(errorIndex) - 1] or '?'))
                    count += 1
                else:

                    #init value
                    tempPortID = ""
                    chassisIdSubType = ""
                    portIdSubType = ""
                    firstData = None
                    secondData = None
                    status = None

                    for i in varBindTable:

                        chassisIdSubType = i[3][1].prettyPrint()
                        portIdSubType = i[4][1].prettyPrint()

                        if chassisIdSubType == "7" and portIdSubType == "2":
                            firstData = i[0][1].prettyPrint()
                            tempPortID = i[1][1].prettyPrint()[2:]  # 00000001
                            # change 00000001 to \x00\x00\x00\x01
                            packer = struct.Struct('bbbb')
                            secondData = packer.pack(int(tempPortID[0:2], 16),
                                                     int(tempPortID[2:4], 16),
                                                     int(tempPortID[4:6], 16),
                                                     int(tempPortID[6:8], 16))
                            status = True
                        elif chassisIdSubType == "4" and portIdSubType == "3":
                            firstData = i[0][1].prettyPrint()
                            secondData = i[2][1].prettyPrint()
                            status = False
                        """ 
                            key = poistion of active port at recvice remote data in snmp (int : 2)
                            index 0 = datapath id (str : dpid:0000000000000001)
                            index 1 = port no (binary : b'\x00\x00\x00\x01')
                            index 2 = check status (datapath_id, port_no) or (hw_addr, hw_desc)
                        """
                        dictRemoteSwitchDataFromPort[str(
                            i[0][0][-2])] = [firstData, secondData, status]

                        print("dictRemoteSwitchDataFromPort : ")
                        print("key : " + str(i[0][0][-2]))
                        print(
                            "index 0 : " +
                            dictRemoteSwitchDataFromPort[str(i[0][0][-2])][0])
                        print("index 1 : " + str(dictRemoteSwitchDataFromPort[
                            str(i[0][0][-2])][1]))
                        print("index 2 : " + str(dictRemoteSwitchDataFromPort[
                            str(i[0][0][-2])][2]))

                    #print("remote port list : ")
                    #print(dictRemoteSwitchDataFromPort)
                    return dictRemoteSwitchDataFromPort
            # </snmpv2c>
        except Exception as err:
            print(" 277 Switch ip " + self.switchIp +
                  " handling run-time error : " + str(err))
Example #14
0
    def getPortFromSnmpVersion2C(self, mininetOption):

        # init value
        count = 0
        cmdGen = None

        # list port
        dictPort = {}

        try:
            # create object for create snmp command
            cmdGen = cmdgen.CommandGenerator()
        except Exception as err:
            print(" 94 Switch ip " + self.switchIp +
                  " terminate because handling run-time error : " + str(err))
            sys.exit()

        while count < self.numberOfRetransmission:
            try:
                # connect to snmp at switch
                errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
                    cmdgen.CommunityData('public'),
                    cmdgen.UdpTransportTarget((self.switchIp, 161)),
                    '1.0.8802.1.1.2.1.3.7.1.3', '1.0.8802.1.1.2.1.3.7.1.4')

                if errorIndication:
                    print(errorIndication)
                    count += 1
                else:
                    if errorStatus:
                        print(
                            '%s at %s' %
                            (errorStatus.prettyPrint(), errorIndex
                             and varBindTable[-1][int(errorIndex) - 1] or '?'))
                        count += 1
                    else:
                        # init value
                        #index = 1

                        # number of port
                        if mininetOption == 1 and len(varBindTable) > 0:
                            del varBindTable[len(varBindTable) - 1]

                        # check number of port should > 0
                        if (len(varBindTable) > 0):

                            for i in varBindTable:

                                # mac address
                                tempHwAddr = i[0][1].prettyPrint()
                                tempHwAddr = tempHwAddr[2:len(tempHwAddr)]

                                if (len(tempHwAddr) != 12):
                                    print(
                                        "Error invalid mac address from local port in snmp"
                                    )
                                else:

                                    tempHwAddr = tempHwAddr[
                                        0:2] + ":" + tempHwAddr[
                                            2:4] + ":" + tempHwAddr[
                                                4:6] + ":" + tempHwAddr[
                                                    6:8] + ":" + tempHwAddr[
                                                        8:
                                                        10] + ":" + tempHwAddr[
                                                            10:12]
                                    tempPPort = PPort(i[0][0][-1], tempHwAddr,
                                                      i[1][1].prettyPrint(), 0,
                                                      0, 192, 0, 0, 0)

                                    dictPort[str(
                                        i[0][0][-1]
                                    )] = tempPPort  # type interger chage to str
                                    """
                                    print("key : " + str(i[0][0][-1]) )
                                    print("item  : " + tempPPort )
                                    
                                    """
                                    """
                                        key : poistion of active port in snmp (2)
                                        item : PPort(object)
                                    """

                                #index += 1

                            return dictPort

                        else:
                            print(
                                " 159 Switch ip " + self.switchIp +
                                " terminate because : switch doesn't have active port please snmp"
                            )
                            sys.exit()

            except Exception as err:
                count += 1
                print(" 165 Switch ip " + self.switchIp +
                      " handling run-time error : " + str(err))

        print(" Switch ip " + self.switchIp +
              " terminate because : it has problem about snmp ")
        sys.exit()
Example #15
0
from pysnmp.entity.rfc3413.oneliner import cmdgen

snmpCmdGen = cmdgen.CommandGenerator()
snmpTransportData = cmdgen.UdpTransportTarget(('localhost', 161))
mib = cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0)
error, errorStatus, errorIndex, binds = snmpCmdGen.getCmd(cmdgen.CommunityData("public"), snmpTransportData, mib)
if error:
    print "Error "+error
else:
    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and binds[int(errorIndex)-1] or '?'
            )
        )
    else:
        for name, val in binds:
            print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
# Array of messages to print after first line if verbose
stateMessages = []

# Performance data for each sensor as string
perfData = []

# Root for sensor dictionary tree
sensors = {}

# Root for sensor OIDs
sensorsOID = (1, 3, 6, 1, 4, 1, 26840, 254, 1, 1, 1, 1)

generator = cmdgen.CommandGenerator()
communityData = cmdgen.CommunityData(community)
transport = cmdgen.UdpTransportTarget((hostname, port), timeout=timeout, retries=0)
command = getattr(generator, 'nextCmd')

errorIndication, errorStatus, errorIndex, result = command(communityData, transport, sensorsOID)

# Check if an exception occurred
if errorIndication:
    print "%s NETWAYS Monitor: %s" % (NagiosState.UNKNOWN.name, errorIndication)
    mostImportantState = NagiosState.UNKNOWN
elif errorStatus:
    print('%s NETWAYS Monitor: %s at %s' % (NagiosState.CRITICAL.name,
                                             errorStatus.prettyPrint(),
                                             errorIndex and result[int(errorIndex)-1] or '?'))
    mostImportantState = NagiosState.CRITICAL
else:
    # Sort results
Example #17
0
# SET Command Generator
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto import rfc1902

errorIndication, errorStatus, \
                 errorIndex, varBinds = cmdgen.CommandGenerator().setCmd(
    # SNMP v1
    #    cmdgen.CommunityData('test-agent', 'public', 0),
    # SNMP v2
    #    cmdgen.CommunityData('test-agent', 'public'),
    # SNMP v3
    cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'),
    cmdgen.UdpTransportTarget(('localhost', 161)),
    # MIB symbol name, plain string value
    ((('SNMPv2-MIB', 'sysName'), 0), 'new name'),
    # Plain OID name, rfc1902 class instance value
    ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('new name'))
    )

if errorIndication:
    print errorIndication
else:
    if errorStatus:
        print '%s at %s\n' % (errorStatus.prettyPrint(),
                              varBinds[int(errorIndex) - 1])
    else:
        for name, val in varBinds:
            print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
Example #18
0
    def set_multiple(self, oid):
        """
        Sets a single OID value. If you do not pass value_type hnmp will
        try to guess the correct type. Autodetection is supported for:

        * int and float (as Integer, fractional part will be discarded)
        * IPv4 address (as IpAddress)
        * str (as OctetString)

        Unfortunately, pysnmp does not support the SNMP FLOAT type so
        please use Integer instead.
        """

        varbindlist = list()
        snmpsecurity = self._get_snmp_security()
        for i in range(len(oid)):
            value_type = None
            value = oid[i][1]
            if len(oid[i]) == 3:
                value_type = oid[i][2]

            if value_type is None:
                if isinstance(value, int):
                    data = Integer(value)
                elif isinstance(value, float):
                    data = Integer(value)
                elif isinstance(value, str):
                    if is_ipv4_address(value):
                        data = IpAddress(value)
                    else:
                        data = OctetString(value)
                else:
                    raise TypeError(
                        "Unable to autodetect type. Please pass one of "
                        "these strings as the value_type keyword arg: "
                        ", ".join(TYPES.keys()))
            else:
                if value_type not in TYPES:
                    raise ValueError(
                        "'{}' is not one of the supported types: {}".format(
                            value_type, ", ".join(TYPES.keys())))
                data = TYPES[value_type](value)
            oid_tup = (oid[i][0], data)
            varbindlist.append(oid_tup)

        try:
            engine_error, pdu_error, pdu_error_index, objects = self._cmdgen.setCmd(
                snmpsecurity,
                cmdgen.UdpTransportTarget((self.host, self.port),
                                          timeout=self.timeout,
                                          retries=self.retries), *varbindlist)
            if engine_error:
                raise SNMPError(engine_error)
            if pdu_error:
                raise SNMPError(pdu_error.prettyPrint())
        except Exception as e:
            raise SNMPError(e)

        _, value = objects[0]
        value = convert_value_to_native(value)
        return value
Example #19
0
from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

for n in range(1, 3):
    server_ip="192.168.20.{0}".format(n)
    print ("\nFetching stats for...", server_ip)
    errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(
        cmdgen.CommunityData('mytest'),
        cmdgen.UdpTransportTarget((server_ip, 161)),
        0,25,
        '1.3.6.1.2.1.2.2.1.2'
    )

    for varBindTableRow in varBindTable:
        for name, val in varBindTableRow:
            print('%s = Interface Name: %s' % (name.prettyPrint(), val.prettyPrint()))


from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
    cmdgen.CommunityData('public'),
    #cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)),
    cmdgen.UdpTransportTarget(('127.0.0.1', 161)),
    '1.3.6.1.2.1.1.1.0',
    '1.3.6.1.2.1.1.6.0',
    '1.3.6.1.4.1.311')

# 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()))
snmpUsername = "******"
# Port Status Displayed Information
statusID = {
    1: "Disabled",
    2: "Blocking",
    3: "Listening",
    4: "Learning",
    5: "Forwarding",
    6: "Broken"
}
#################################################################################################

# Retrieve VLAN Table
errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator(
).nextCmd(cmdgen.CommunityData('agent', snmpUsername, 0),
          cmdgen.UdpTransportTarget((deviceIPAddress, snmpPort)),
          (1, 3, 6, 1, 4, 1, 9, 9, 46, 1, 3, 1, 1, 2))
# Store VLAN Table
vlans = []
for row in varBinds:
    for item in row:
        vlans.append(item[0][15])
# Retrieve STP port status information
vlanAndSTP = {}
for vlan in vlans:
    username = '******' % (snmpUsername, vlan)
    errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator(
    ).nextCmd(cmdgen.CommunityData('agent', username, 0),
              cmdgen.UdpTransportTarget((deviceIPAddress, snmpPort)),
              (1, 3, 6, 1, 2, 1, 17, 2, 15, 1, 3))
    # Store STP port status information
Example #22
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_lib('pysnmp'),
                         exception=PYSNMP_IMP_ERR)

    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'] is False:
            module.fail_json(msg='Community not set when using snmp version 2')

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

        if m_args['level'] == "authPriv" and m_args['privacy'] is 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)

    def Tree():
        return 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.ifSpeed 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 current_interface not 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)
Example #23
0
# SNMP Agent Configuration Details (i.e. Murdock)

agent_ip = '139.63.246.111'
agent_port = 161
community = 'public'

# SNMP MIB OID for interface operating status statistics (Object : ifOperStatus, OID : 1.3.6.1.2.1.2.2.1.8)

if_op_status = (1, 3, 6, 1, 2, 1, 2, 2, 1, 8)

# Configuring PySNMP module to poll SNMP interface operating status statistics - SNMP Version : v2c

generator = cmdgen.CommandGenerator()
comm_data = cmdgen.CommunityData('Murdock', community, 1)
transport = cmdgen.UdpTransportTarget((agent_ip, agent_port))

# Physical interface to SNMP IfIndex mapping

with open("Config/Device_Interfaces/Murdock_Interface_List.json") as json_file:
    if_list = {}
    if_list = json.load(json_file)

# Monitoring interfaces for failure events - SNMP polling interval is 20 seconds

while True:

    if_stat_call = getattr(generator, 'nextCmd')
    response = (errorIndication, errorStatus, errorIndex, varBinds)\
             = if_stat_call(comm_data, transport, if_op_status)
    if_stat = response[3]
Example #24
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()
            current_val = val.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)

    module.exit_json(ansible_facts=results)
Example #25
0
    def get_cred(self, snmp_creds):
        for cred in snmp_creds:
            cmdGen = cmdgen.CommandGenerator()

            #SNMPv2
            if (cred['ver'] == 2):
                community = cred['community']

                errIndication, errStatus, errIndex, varBinds = cmdGen.getCmd(
                    cmdgen.CommunityData(community),
                    cmdgen.UdpTransportTarget((self._ip, SNMP_PORT)),
                    '1.3.6.1.2.1.1.5.0',
                    lookupNames=False,
                    lookupValues=False)

                if errIndication:
                    continue
                else:
                    self.ver = 2
                    self.success = 1
                    self.v2_community = community
                    self.v3Username = None
                    self.v3AuthKey = None
                    self.v3PrivKey = None
                    self.v3AuthProtocol = None
                    self.v3PrivProtocol = None

                    return 1

            #SNMPv3
            if (cred['ver'] == 3):
                community = cred['community']

                v3Username = cred['v3Username']

                v3AuthProtocol = cmdgen.usmNoAuthProtocol
                if 'v3AuthProtocol' in cred:
                    if cred['v3AuthProtocol'] == 'MD5':
                        v3AuthProtocol = cmdgen.usmHMACMD5AuthProtocol
                    if cred['v3AuthProtocol'] == 'SHA':
                        v3AuthProtocol = cmdgen.usmHMACSHAAuthProtocol

                v3PrivProtocol = cmdgen.usmNoPrivProtocol
                if 'v3PrivProtocol' in cred:
                    if cred['v3PrivProtocol'] == 'DES':
                        v3PrivProtocol = cmdgen.usmDESPrivProtocol
                    if cred['v3PrivProtocol'] == '3DES':
                        v3PrivProtocol = cmdgen.usm3DESEDEPrivProtocol
                    if cred['v3PrivProtocol'] == 'AES128':
                        v3PrivProtocol = cmdgen.usmAesCfb128Protocol
                    if cred['v3PrivProtocol'] == 'AES192':
                        v3PrivProtocol = cmdgen.usmAesCfb192Protocol
                    if cred['v3PrivProtocol'] == 'AES256':
                        v3PrivProtocol = cmdgen.usmAesCfb256Protocol

                v3AuthKey = None
                v3PrivKey = None

                if (v3AuthProtocol != cmdgen.usmNoAuthProtocol):
                    v3AuthKey = cred['v3AuthKey']
                if (v3PrivProtocol != cmdgen.usmNoPrivProtocol):
                    v3PrivKey = cred['v3PrivKey']

                errIndication, errStatus, errIndex, varBinds = cmdGen.getCmd(
                    cmdgen.UsmUserData(v3Username, v3AuthKey, v3PrivKey,
                                       v3AuthProtocol, v3PrivProtocol),
                    cmdgen.UdpTransportTarget((self._ip, SNMP_PORT)),
                    '1.3.6.1.2.1.1.5.0',
                    lookupNames=False,
                    lookupValues=False)

                if errIndication:
                    continue
                else:
                    self.ver = 3
                    self.success = 1
                    self.v2_community = community
                    self.v3Username = v3Username
                    self.v3AuthProtocol = v3AuthProtocol
                    self.v3PrivProtocol = v3PrivProtocol
                    self.v3AuthKey = v3AuthKey
                    self.v3PrivKey = v3PrivKey

                    return 1

            return 0
Example #26
0
def snmpwalk(snmp_host, snmp_port, snmp_community, oid):
    global name_list, path_list, port_list, addr_list
    global ladd, lprt, radd, rprt, cond, status, id_list
    global param_list, ifindex, ifdescr, ifmac, iftype
    global ifmtu, ifspeed, ifinoc, ifoutoc, ifstatus
    global ifidv, ipaddrv, netmaskv, bcastv, destv
    global hopv, maskv, metricv

    cmd_gen = cmdgen.CommandGenerator()

    error_indication, error_status, error_index, var_bind_table = cmd_gen.nextCmd(
        cmdgen.CommunityData(snmp_community),
        cmdgen.UdpTransportTarget((snmp_host, snmp_port)), oid)

    if error_status:
        print('%s at %s' %
              (error_status.prettyPrint(), error_index
               and var_bind_table[-1][int(error_index) - 1] or '?'))
    else:
        for varBindTableRow in var_bind_table:
            for name, val in varBindTableRow:
                # for process information
                if key == 'Name':
                    name_list += val.prettyPrint().split("\n")

                elif key == 'Path':
                    path_list += val.prettyPrint().split("\n")

                elif key == 'id':
                    id_list += val.prettyPrint().split("\n")

                elif key == 'status':
                    if val.prettyPrint() == str(1):
                        status += 'running',

                    elif val.prettyPrint() == str(2):
                        status += 'runnable',

                    else:
                        status += 'unknown',

                elif key == 'Param':
                    param_list += val.prettyPrint().split("\n")
                # for routing information
                elif key == "dest":
                    destv += val.prettyPrint().split("\n")
                elif key == "hop":
                    hopv += val.prettyPrint().split("\n")
                elif key == "mask":
                    maskv += val.prettyPrint().split("\n")
                elif key == "metric":
                    metricv += val.prettyPrint().split("\n")
                # for network ip information
                elif key == "ifid":
                    ifidv += val.prettyPrint().split("\n")
                elif key == "ipaddr":
                    ipaddrv += val.prettyPrint().split("\n")
                elif key == "netmask":
                    netmaskv += val.prettyPrint().split("\n")
                elif key == "bcast":
                    bcastv += val.prettyPrint().split("\n")
                # for network interfaces
                elif key == 'index':
                    ifindex += val.prettyPrint().split("\n")
                elif key == 'descr':
                    ifdescr += val.prettyPrint().split("\n")
                elif key == 'mac':
                    ifmac += val.prettyPrint().split("\n")
                elif key == 'type':
                    iftype += val.prettyPrint().split("\n")
                elif key == 'mtu':
                    ifmtu += val.prettyPrint().split("\n")
                elif key == 'speed':
                    ifspeed += val.prettyPrint().split("\n")
                elif key == 'inoc':
                    ifinoc += val.prettyPrint().split("\n")
                elif key == 'outoc':
                    ifoutoc += val.prettyPrint().split("\n")
                elif key == 'cur_status':
                    ifstatus += val.prettyPrint().split("\n")
                # for udp detection
                elif key == 'uaddress':
                    addr_list += val.prettyPrint().split("\n")

                elif key == 'uport':
                    port_list += val.prettyPrint().split("\n")
                # for tcp detection
                elif key == 'taddress':
                    ladd += val.prettyPrint().split("\n")

                elif key == 'tport':
                    lprt += val.prettyPrint().split("\n")

                elif key == 'raddress':
                    radd += val.prettyPrint().split("\n")

                elif key == 'rport':
                    rprt += val.prettyPrint().split("\n")

                elif key == 'state':
                    cond += val.prettyPrint()

                else:
                    print('%s: %s' % (key, val.prettyPrint()))
Example #27
0
    def _fetch_snmp_data(self, nsx_mgr_ip, community_string, mib_string, port):
        cmdGen = cmdgen.CommandGenerator()

        if mib_string == 'HOST-RESOURCES-MIB':
            error_indication, error_status, error_index, var_binds = \
                cmdGen.getCmd(
                    cmdgen.CommunityData(community_string),
                    cmdgen.UdpTransportTarget((nsx_mgr_ip, port)),
                    cmdgen.MibVariable(mib_string, 'hrSystemUptime', '0'),
                    cmdgen.MibVariable(mib_string, 'hrSystemDate', '0'),
                    cmdgen.MibVariable(mib_string, 'hrSystemInitialLoadDevice',
                                       '0'),
                    cmdgen.MibVariable(mib_string,
                                       'hrSystemInitialLoadParameters', '0'),
                    cmdgen.MibVariable(mib_string, 'hrSystemNumUsers', '0'),
                    cmdgen.MibVariable(mib_string, 'hrSystemProcesses', '0'),
                    cmdgen.MibVariable(mib_string, 'hrSystemMaxProcesses',
                                       '0'),
                    cmdgen.MibVariable(mib_string, 'hrMemorySize', '0'),
                    lookupNames=True, lookupValues=True)
            self._print_mib_info(error_indication, error_status, var_binds)
            return var_binds

        elif mib_string == 'SNMPv2-MIB':
            error_indication, error_status, error_index, var_binds = \
                cmdGen.getCmd(
                    cmdgen.CommunityData(community_string),
                    cmdgen.UdpTransportTarget((nsx_mgr_ip, port)),
                    cmdgen.MibVariable(mib_string, 'sysDescr', 0),
                    cmdgen.MibVariable(mib_string, 'sysObjectID', 0),
                    cmdgen.MibVariable(mib_string, 'sysUpTime', 0),
                    cmdgen.MibVariable(mib_string, 'sysContact', 0),
                    cmdgen.MibVariable(mib_string, 'sysName', 0),
                    cmdgen.MibVariable(mib_string, 'sysLocation', 0),
                    cmdgen.MibVariable(mib_string, 'sysServices', 0),
                    lookupNames=True, lookupValues=True)
            self._print_mib_info(error_indication, error_status, var_binds)
            return var_binds

        elif mib_string == 'IF-MIB':
            error_indication, error_status, error_index, var_binds = \
                cmdGen.getCmd(
                    cmdgen.CommunityData(community_string),
                    cmdgen.UdpTransportTarget((nsx_mgr_ip, port)),
                    cmdgen.MibVariable(mib_string, 'ifNumber', 0),
                    cmdgen.MibVariable(mib_string, 'ifDescr', 1),
                    cmdgen.MibVariable(mib_string, 'ifDescr', 2),
                    cmdgen.MibVariable(mib_string, 'ifDescr', 3),
                    cmdgen.MibVariable(mib_string, 'ifType', 1),
                    cmdgen.MibVariable(mib_string, 'ifType', 2),
                    cmdgen.MibVariable(mib_string, 'ifType', 3),
                    cmdgen.MibVariable(mib_string, 'ifMtu', 1),
                    cmdgen.MibVariable(mib_string, 'ifMtu', 2),
                    cmdgen.MibVariable(mib_string, 'ifMtu', 3),
                    cmdgen.MibVariable(mib_string, 'ifSpeed', 1),
                    cmdgen.MibVariable(mib_string, 'ifSpeed', 2),
                    cmdgen.MibVariable(mib_string, 'ifSpeed', 3),
                    cmdgen.MibVariable(mib_string, 'ifPhysAddress', 1),
                    cmdgen.MibVariable(mib_string, 'ifPhysAddress', 2),
                    cmdgen.MibVariable(mib_string, 'ifPhysAddress', 3),
                    cmdgen.MibVariable(mib_string, 'ifAdminStatus', 1),
                    cmdgen.MibVariable(mib_string, 'ifAdminStatus', 2),
                    cmdgen.MibVariable(mib_string, 'ifAdminStatus', 3),
                    cmdgen.MibVariable(mib_string, 'ifOperStatus', 1),
                    cmdgen.MibVariable(mib_string, 'ifOperStatus', 2),
                    cmdgen.MibVariable(mib_string, 'ifOperStatus', 3),
                    cmdgen.MibVariable(mib_string, 'ifLastChange', 1),
                    cmdgen.MibVariable(mib_string, 'ifLastChange', 2),
                    cmdgen.MibVariable(mib_string, 'ifLastChange', 3),
                    cmdgen.MibVariable(mib_string, 'ifInOctets', 1),
                    cmdgen.MibVariable(mib_string, 'ifInOctets', 2),
                    cmdgen.MibVariable(mib_string, 'ifInOctets', 3),
                    cmdgen.MibVariable(mib_string, 'ifInUcastPkts', 0),
                    cmdgen.MibVariable(mib_string, 'ifInNUcastPkts', 0),
                    cmdgen.MibVariable(mib_string, 'ifInDiscards', 0),
                    cmdgen.MibVariable(mib_string, 'ifInErrors', 0),
                    cmdgen.MibVariable(mib_string, 'ifInUnknownProtos', 0),
                    cmdgen.MibVariable(mib_string, 'ifOutOctets', 0),
                    cmdgen.MibVariable(mib_string, 'ifOutUcastPkts', 0),
                    cmdgen.MibVariable(mib_string, 'ifOutNUcastPkts', 0),
                    cmdgen.MibVariable(mib_string, 'ifOutDiscards', 0),
                    cmdgen.MibVariable(mib_string, 'ifOutErrors', 0),
                    cmdgen.MibVariable(mib_string, 'ifOutQLen', 0),
                    cmdgen.MibVariable(mib_string, 'ifSpecific', 0),
                    cmdgen.MibVariable(mib_string, 'ifOutDiscards', 0),
                    cmdgen.MibVariable(mib_string, 'ifOutDiscards', 0),
                    cmdgen.MibVariable(mib_string, 'ifOutDiscards', 0),
                    lookupNames=True, lookupValues=True)
            self._print_mib_info(error_indication, error_status, var_binds)
            return var_binds
Example #28
0
#!/usr/bin/env python3
# source : http://pysnmp.sourceforge.net/examples/current/v3arch/oneliner/manager/cmdgen/get-v2c.html

# snmpget -v2c -c public -ObentU 192.168.1.101 1.3.6.1.2.1.1.7.0

from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
    cmdgen.CommunityData('public'),
    cmdgen.UdpTransportTarget(('192.168.1.101', 161)), '1.3.6.1.2.1.1.7.0'
    #    ,
    #    '1.3.6.1.2.1.1.6.0'
)

# 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()))
Example #29
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:
            vallisttmp = []
            for varBindTableRow in varBindTable:
                for name, val in varBindTableRow:
                    #                    print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
                    vallisttmp.append(val)
            for i in range(num):
                vallist[i] = vallisttmp[i]
Example #30
0
    def get_data(self):
        #具体的获取逻辑

        # 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 = self.cmdGen.getCmd(
            self.snmp_auth,
            cmdgen.UdpTransportTarget((self.args['host'], 161),
                                      timeout=20,
                                      retries=1),
            cmdgen.MibVariable(p.sysDescr, ),
            cmdgen.MibVariable(p.sysObjectId, ),
            cmdgen.MibVariable(p.sysUpTime, ),
            #cmdgen.MibVariable(p.sysContact, ),
            cmdgen.MibVariable(p.sysName, ),
            cmdgen.MibVariable(p.sysLocation, ),

            #cmdgen.MibVariable(p.sysModel, ),
            lookupMib=False,
            ignoreNonIncreasingOid=True)

        if errorIndication:
            #print errorIndication
            raise ServerError(str(errorIndication))
        #获取系统参数
        for oid, val in varBinds:
            current_oid = oid.prettyPrint()
            current_val = val.prettyPrint()
            if current_oid == v.sysDescr:
                netsysdescr = decode_hex(current_val)
                #results['netsysdescr'] = decode_hex(current_val)
                if 'h3c' in netsysdescr.lower():
                    results['netsysdescr']['brand'] = 'H3C'
                    results['netsysdescr']['version'] = re.compile(
                        'Version(.*), R').findall(netsysdescr)[0]
                    results['netsysdescr']['model'] = re.compile(
                        'H3C(.*)So').findall(netsysdescr)[0]
                elif 'cisco' in netsysdescr.lower(
                ) and 'software' in netsysdescr.lower():
                    results['netsysdescr']['brand'] = 'CISCO'
                    #results['netsysdescr']['version']=re.compile('Version(.*), R').findall(netsysdescr)[0]
                    results['netsysdescr']['version'] = re.compile(
                        'Version(.*) R').findall(netsysdescr)[0]
                    results['netsysdescr']['model'] = re.compile(
                        'Software (.*), V').findall(netsysdescr)[0]
                elif 'cisco' in netsysdescr.lower(
                ) and 'security' in netsysdescr.lower():
                    results['netsysdescr']['brand'] = 'CISCO ASA'
                    results['netsysdescr']['version'] = re.compile(
                        'Version(.*)').findall(netsysdescr)[0]
                    results['netsysdescr']['model'] = 'unsupported'
                elif 'cisco' in netsysdescr.lower(
                ) and 'controller' in netsysdescr.lower():
                    results['netsysdescr']['brand'] = 'CISCO Controller'
                    results['netsysdescr']['version'] = 'unsupported'
                    results['netsysdescr']['model'] = 'unsupported'
                elif 'linux ns' in netsysdescr.lower():
                    results['netsysdescr']['brand'] = 'netentsec'
                    results['netsysdescr']['version'] = re.compile(
                        'NS (.*)-').findall(netsysdescr)[0]
                    results['netsysdescr']['model'] = re.compile(
                        '-(.*) #').findall(netsysdescr)[0]
                elif 'dell' in netsysdescr.lower(
                ) and 'networking' in netsysdescr.lower():
                    results['netsysdescr']['brand'] = 'DELL'
                    results['netsysdescr']['version'] = re.compile(
                        ',(.*),').findall(netsysdescr)[0]
                    results['netsysdescr']['model'] = re.compile(
                        'Networking (.*),').findall(netsysdescr)[0]
                elif 'ds' in netsysdescr.lower():
                    results['netsysdescr']['brand'] = 'EMC'
                    results['netsysdescr']['version'] = 'unsupported'
                    results['netsysdescr']['model'] = netsysdescr
                else:
                    results['netsysdescr']['brand'] = 'unsupported'
                    results['netsysdescr']['version'] = 'unsupported'
                    results['netsysdescr']['model'] = 'unsupported'

            elif current_oid == v.sysObjectId:
                results['netsysobjectid'] = current_val
            elif current_oid == v.sysUpTime:
                results['netsysuptime'] = current_val
            elif current_oid == v.sysName:
                results['netsysname'] = current_val
            elif current_oid == v.sysLocation:
                results['netsyslocation'] = current_val

        errorIndication, errorStatus, errorIndex, varTable = self.cmdGen.nextCmd(
            self.snmp_auth,
            cmdgen.UdpTransportTarget((self.args['host'], 161),
                                      timeout=10,
                                      retries=1),
            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, ),

            #z
            cmdgen.MibVariable(p.ipNetToMediaIfindex, ),
            cmdgen.MibVariable(p.ipNetToMediaPhysAddress, ),
            #cmdgen.MibVariable(p.ipNetToMediaNetAddress, ),
            lookupMib=False,
            ignoreNonIncreasingOid=True)

        if errorIndication:
            raise ServerError(str(errorIndication))

        interface_indexes = []

        all_ipv4_addresses = []
        ipv4_networks = Tree()

        #获取接口数据
        for varBinds in varTable:
            #print varBinds
            for oid, val in varBinds:
                current_oid = oid.prettyPrint()
                current_val = val.prettyPrint()
                #print current_oid
                #print current_val

                if v.ifIndex in current_oid:
                    ifIndex = int(current_oid.rsplit('.', 1)[-1])
                    results['netinterfaces'][ifIndex]['ifindex'] = current_val
                    interface_indexes.append(ifIndex)
                if v.ifDescr in current_oid:
                    ifIndex = int(current_oid.rsplit('.', 1)[-1])
                    results['netinterfaces'][ifIndex]['name'] = current_val
                if v.ifMtu in current_oid:
                    ifIndex = int(current_oid.rsplit('.', 1)[-1])
                    results['netinterfaces'][ifIndex]['mtu'] = current_val
                if v.ifSpeed in current_oid:
                    ifIndex = int(current_oid.rsplit('.', 1)[-1])
                    results['netinterfaces'][ifIndex]['speed'] = current_val
                if v.ifPhysAddress in current_oid:
                    ifIndex = int(current_oid.rsplit('.', 1)[-1])
                    results['netinterfaces'][ifIndex]['mac'] = decode_mac(
                        current_val)
                if v.ifAdminStatus in current_oid:
                    ifIndex = int(current_oid.rsplit('.', 1)[-1])
                    results['netinterfaces'][ifIndex][
                        'adminstatus'] = lookup_adminstatus(int(current_val))
                if v.ifOperStatus in current_oid:
                    ifIndex = int(current_oid.rsplit('.', 4)[-1])
                    results['netinterfaces'][ifIndex][
                        'operstatus'] = lookup_operstatus(int(current_val))
                if v.ifAlias in current_oid:
                    ifIndex = int(current_oid.rsplit('.', 1)[-1])
                    results['netinterfaces'][ifIndex][
                        'description'] = current_val

                #z
                if v.ipNetToMediaIfindex in current_oid:
                    iptoindex = ".".join(current_oid.split('.')[-4::])
                    results['netipto'][iptoindex]['index'] = int(current_val)
                else:
                    results['netipto']['ip']['index'] = 'unsupported'
                if v.ipNetToMediaPhysAddress in current_oid:
                    iptomac = ".".join(current_oid.split('.')[-4::])
                    results['netipto'][iptomac]['mac'] = decode_mac(
                        current_val)
                else:
                    results['netipto']['ip']['mac'] = 'unsupported'
                #if v.ipNetToMediaNetAddress in current_oid:
                #    iptoip = ".".join(current_oid.split('.')[-4::])
                #    results['netipto'][iptoip]['ip'] = 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

        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['netinterfaces'][int(
                interface)]['ipv4'] = interface_to_ipv4[interface]

        results['netall_ipv4_addresses'] = all_ipv4_addresses

        return dict(results)