def udp6transporttarget(self):
     """
     Creates IPV6 UDP transport object
     Returns: IPv6 UDPTransport object
     """
     return cmdgen.Udp6TransportTarget((self.ipaddr, self.port),
                                      timeout=self.timeout, retries=3)
示例#2
0
    def SetTrasnportLayerParams(self,
                                ip_addr,
                                port_id=161,
                                timeout_val=1,
                                retries_num=5):
        """
        :param ip_addr: Hostname or Ip address string
        :type ip_addr: str
        :param port_id: L4 port number
        :type port_id: int
        :param timeout_val: Response timeout in seconds
        :type timeout_val: int
        :param retries_num: Maximum number of request retries, 0 retries means just a single request.
        :type retries_num: int
        """
        function_name = self.SetTrasnportLayerParams.__name__

        if 1 <= port_id <= 65535:
            self.InputParams.port = port_id
        else:
            raise ArgumentError(
                "Invalid L4 port number: " + str(port_id) +
                ". Should be an integer in range 0-65535.", function_name)

        if isinstance(timeout_val, int) and timeout_val >= 0:
            self.InputParams.timeout = timeout_val
        else:
            raise ArgumentError(
                "Illegal timeout value: " + str(timeout_val) +
                ". Should be a positive integer or "
                "zero.", function_name)

        if isinstance(retries_num, int) and retries_num >= 0:
            self.InputParams.retries = retries_num
        else:
            raise ArgumentError(
                "Illegal retries value: " + str(retries_num) +
                ". Should be a positive integer or "
                "zero.", function_name)

        if IsValidIpv4Address(ip_addr) or IsValidIpv6Address(ip_addr):
            self.InputParams.ip = ip_addr
            if IsValidIpv4Address(ip_addr):
                self.UdpTransportTarget = cmdgen.UdpTransportTarget(
                    (self.InputParams.ip, self.InputParams.port),
                    self.InputParams.timeout, self.InputParams.retries)
            else:
                self.UdpTransportTarget = cmdgen.Udp6TransportTarget(
                    (self.InputParams.ip, self.InputParams.port),
                    self.InputParams.timeout, self.InputParams.retries)
        else:
            raise ArgumentError(
                "Illegal IP address: " + ip_addr +
                ". Should be a valid Ipv4 or Ipv6 "
                "adress.", function_name)
示例#3
0
文件: request.py 项目: nomed/rnms
def _get_host_transport(host_addr):
    """ Return the correct transport target for
    the given host """
    try:
        addrinfo = socket.getaddrinfo(host_addr, 0)[0]
    except socket.gaierror:
        return None
    if addrinfo[0] == socket.AF_INET:
        return cmdgen.UdpTransportTarget((host_addr, 161))
    elif addrinfo[0] == socket.AF_INET6:
        return cmdgen.Udp6TransportTarget((host_addr, 161))
    raise ValueError('unknown transport type')
示例#4
0
 def transport(self):
     """
     Get the SNMP transport taking into consideration ipv4/ipv6
     :return: SNMP transport
     """
     if self.ipv6():
         transport = cmdgen.Udp6TransportTarget(
             (self.destination(), self.port()))
     else:
         transport = cmdgen.UdpTransportTarget(
             (self.destination(), self.port()), timeout=5)
     return transport
示例#5
0
def get_transport(conf):
    """
    Get the SNMP transport taking into consideration ipv4/ipv6
    :param conf:
    :return: SNMP transport
    """
    destination = conf.get("destination")
    port = int(conf.get("port", 161))
    ipv6 = int(conf.get("ipv6", 0))

    if ipv6:
        transport = cmdgen.Udp6TransportTarget((destination, port))
    else:
        transport = cmdgen.UdpTransportTarget((destination, port))
    return transport
示例#6
0
文件: bulkgen.py 项目: ithek/pysnmp
            for name, val in varBindTableRow:
                print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))

# Send a series of SNMP GETBULK requests
#     with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols
#     over IPv6/UDP
#     to an Agent at [::1]:161
#     with values non-repeaters = 1, max-repetitions = 25
#     for IP-MIB::ipAdEntAddr and all columns of the IF-MIB::ifEntry table
#     stop when response OIDs leave the scopes of the table OR maxRows == 20
#     perform response OIDs and values resolution at MIB
# make sure IF-MIB.py and IP-MIB.py are in search path

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(
    cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
    cmdgen.Udp6TransportTarget(('::1', 161)),
    1,
    25,
    cmdgen.MibVariable('IP-MIB', 'ipAdEntAddr'),
    cmdgen.MibVariable('IF-MIB', 'ifEntry'),
    lookupNames=True,
    lookupValues=True,
    maxRows=20)

if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?'))
示例#7
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
示例#8
0
def do_run():

    config = get_input_config()

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

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

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

    destination_list = config.get("destination")

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

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

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

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

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

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

    global RESPONSE_HANDLER_INSTANCE
    RESPONSE_HANDLER_INSTANCE = class_(**response_handler_args)

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

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

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

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

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

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

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

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

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

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

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

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

    mibBuilder = cmdGen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    mibSources = (builder.DirMibSource(mib_egg_dir), )

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

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

    if mib_names_args:
        mibBuilder.loadModules(*mib_names_args)

    global mibView
    mibView = view.MibViewController(mibBuilder)

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

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

        mp_model_val = 1

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

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

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

            apt = AttributePollerThread(cmdGen, destination, port, transport,
                                        snmp_version, do_bulk, do_subtree,
                                        security_object, snmpinterval,
                                        non_repeaters, max_repetitions,
                                        oid_args, split_bulk_output)
            apt.start()
示例#9
0
# ( ( authData, transportTarget, varNames ), ... )
targets = (
    # 1-st target (SNMPv1 over IPv4/UDP)
    (cmdgen.CommunityData('public', mpModel=0),
     cmdgen.UdpTransportTarget(
         ('demo.snmplabs.com', 161)), ('1.3.6.1.2.1', '1.3.6.1.3.1')),
    # 2-nd target (SNMPv2c over IPv4/UDP)
    (cmdgen.CommunityData('public'),
     cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ('1.3.6.1.4.1', )),
    # 3-nd target (SNMPv3 over IPv4/UDP)
    (cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
     cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)),
     (cmdgen.MibVariable('SNMPv2-MIB', 'system'), )),
    # 4-th target (SNMPv3 over IPv6/UDP)
    (cmdgen.UsmUserData('usr-md5-none', 'authkey1'),
     cmdgen.Udp6TransportTarget(
         ('::1', 161)), (cmdgen.MibVariable('IF-MIB', 'ifTable'), ))
    # N-th target
    # ...
)


# Wait for responses or errors, submit GETNEXT requests for further OIDs
def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBindTable, cbCtx):
    (varBindHead, authData, transportTarget) = cbCtx
    print('%s via %s' % (authData, transportTarget))
    if errorIndication:
        print(errorIndication)
        return
    if errorStatus:
        print('%s at %s' %
示例#10
0
def do_run():

    config = get_input_config()
    #params
    snmp_mode = config.get("snmp_mode", "")
    destination = config.get("destination")
    port = int(config.get("port", 161))
    snmpinterval = int(config.get("snmpinterval", 60))
    ipv6 = int(config.get("ipv6", 0))

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

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

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

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

    global RESPONSE_HANDLER_INSTANCE
    RESPONSE_HANDLER_INSTANCE = class_(**response_handler_args)

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

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

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

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

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

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

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

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

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

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

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

    mibBuilder = cmdGen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    mibSources = (builder.DirMibSource(mib_egg_dir), )

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

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

    if mib_names_args:
        mibBuilder.loadModules(*mib_names_args)

    global mibView
    mibView = view.MibViewController(mibBuilder)

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

    if not (object_names is None) and not (destination is None):
        try:

            if ipv6:
                transport = cmdgen.Udp6TransportTarget((destination, port))
            else:
                transport = cmdgen.UdpTransportTarget((destination, port))

            mp_model_val = 1

            if snmp_version == "1":
                mp_model_val = 0

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

            while True:
                if do_bulk and not snmp_version == "1":
                    try:
                        errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(
                            security_object,
                            transport,
                            non_repeaters,
                            max_repetitions,
                            *oid_args,
                            lookupNames=True,
                            lookupValues=True)
                    except:  # catch *all* exceptions
                        e = sys.exc_info()[1]
                        logging.error("Exception with bulkCmd to %s:%s: %s" %
                                      (destination, port, str(e)))
                        time.sleep(float(snmpinterval))
                        continue
                else:
                    try:
                        errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
                            security_object,
                            transport,
                            *oid_args,
                            lookupNames=True,
                            lookupValues=True)
                    except:  # catch *all* exceptions
                        e = sys.exc_info()[1]
                        logging.error("Exception with getCmd to %s:%s: %s" %
                                      (destination, port, str(e)))
                        time.sleep(float(snmpinterval))
                        continue

                if errorIndication:
                    logging.error(errorIndication)
                elif errorStatus:
                    logging.error(errorStatus)
                else:
                    if do_bulk:
                        handle_output(varBindTable,
                                      destination,
                                      table=True,
                                      split_bulk_output=split_bulk_output)
                    else:
                        handle_output(varBinds,
                                      destination,
                                      table=False,
                                      split_bulk_output=split_bulk_output)

                time.sleep(float(snmpinterval))

        except:  # catch *all* exceptions
            e = sys.exc_info()[1]
            logging.error("Looks like an error: %s" % str(e))
            sys.exit(1)
示例#11
0
                                                0))),
    # 3-nd target (SNMPv2c over IPv4/UDP) - same community and
    # different transport address.
    (cmdgen.CommunityData('public'),
     cmdgen.UdpTransportTarget(('localhost', 161)),
     (cmdgen.MibVariable('SNMPv2-MIB', 'sysContact',
                         0), cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0))),
    # 4-nd target (SNMPv3 over IPv4/UDP)
    (cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
     cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)),
     (cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr',
                         0), cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation',
                                                0))),
    # 5-th target (SNMPv3 over IPv6/UDP)
    (cmdgen.UsmUserData('usr-md5-none', 'authkey1'),
     cmdgen.Udp6TransportTarget(
         ('::1', 161)), (cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0),
                         cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0))),
    # N-th target
    # ...
)


# Wait for responses or errors
def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBinds, cbCtx):
    (authData, transportTarget) = cbCtx
    print('%s via %s' % (authData, transportTarget))
    if errorIndication:
        print(errorIndication)
        return 1
    if errorStatus:
示例#12
0
文件: nextgen.py 项目: ithek/pysnmp
# ( ( authData, transportTarget, varNames ), ... )
targets = (
    # 1-st target (SNMPv1 over IPv4/UDP)
    (cmdgen.CommunityData('public', mpModel=0),
     cmdgen.UdpTransportTarget(
         ('localhost', 161)), ((1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 3, 1))),
    # 2-nd target (SNMPv2c over IPv4/UDP)
    (cmdgen.CommunityData('public'),
     cmdgen.UdpTransportTarget(('localhost', 161)), ((1, 3, 6, 1, 4, 1), )),
    # 3-nd target (SNMPv3 over IPv4/UDP)
    (cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
     cmdgen.UdpTransportTarget(('localhost', 161)), ((1, 3, 6, 1, 5, 1), )),
    # 4-th target (SNMPv3 over IPv6/UDP)
    (cmdgen.UsmUserData('usr-md5-none',
                        'authkey1'), cmdgen.Udp6TransportTarget(
                            ('::1', 161)), ((1, 3, 6, 1, 6, 1), )),
    # 5-th target (SNMPv2c over Local Domain Socket)
    (cmdgen.CommunityData('public'),
     cmdgen.UnixTransportTarget('/tmp/snmp-agent'), ((1, 3, 6, 1, 6, 1), ))
    # N-th target
    # ...
)


def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBindTable, cbCtx):
    (varBindHead, authData, transportTarget) = cbCtx
    print('%s via %s' % (authData, transportTarget))
    if errorIndication:
        print(errorIndication)
        return 1