Python pysnmp.entity.rfc3413.oneliner.cmdgen.UdpTransportTarget() Examples

The following are 29 code examples of pysnmp.entity.rfc3413.oneliner.cmdgen.UdpTransportTarget(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pysnmp.entity.rfc3413.oneliner.cmdgen , or try the search function .
Example #1
Source File: nmap_all_server.py    From imoocc with GNU General Public License v2.0 7 votes vote down vote up
def sn_query(self,ip,sn_oid):
        try:
            cg = cmdgen.CommandGenerator()
            errorIndication,errorStatus,errorIndex,varBinds = cg.getCmd(
                cmdgen.CommunityData('server',self.community,1),
                cmdgen.UdpTransportTarget((ip,161)),
                '%s'%sn_oid
            )
            result = str(varBinds[0][1]) if varBinds[0][1] else ""
            logger.info("try nmap net device:%s"%result)

        except Exception as e:
            # import traceback
            # print traceback.print_exc()
            logger.exception("try nmap net device exception:%s"%e)
            result = None
        return result 
Example #2
Source File: nmap_all_server.py    From imoocc with GNU General Public License v2.0 7 votes vote down vote up
def sysname_query(self,ip):
        try:
            cg = cmdgen.CommandGenerator()
            errorIndication,errorStatus,errorIndex,varBinds = cg.getCmd(
                cmdgen.CommunityData('server',self.community,1),
                cmdgen.UdpTransportTarget((ip,161)),
                '%s'%self.sysname_oid
            )
            result = str(varBinds[0][1]) if varBinds[0][1] else ""
            logger.info("try nmap net device:%s"%result)

        except Exception as e:
            # import traceback
            # print traceback.print_exc()
            logger.exception("try nmap net device exception:%s"%e)
            result = None
        return result 
Example #3
Source File: snmp.py    From natlas with GNU General Public License v2.0 7 votes vote down vote up
def get_val(self, oid):
        cmdGen = cmdgen.CommandGenerator()
        errIndication, errStatus, errIndex, varBinds = cmdGen.getCmd(
                        cmdgen.CommunityData(self.v2_community),
                        cmdgen.UdpTransportTarget((self._ip, SNMP_PORT), retries=2),
                        oid, lookupNames = False, lookupValues = False
        )

        if errIndication:
            print('[E] get_snmp_val(%s): %s' % (self.v2_community, errIndication))
        else:
            r = varBinds[0][1].prettyPrint()
            if ((r == OID_ERR) | (r == OID_ERR_INST)):
                return None
            return r

        return None


    #
    # Get bulk SNMP value at OID.
    #
    # Returns 1 on success, 0 on failure.
    # 
Example #4
Source File: pysnmp_3.py    From Mastering-Python-Networking with MIT License 6 votes vote down vote up
def snmp_query(host, community, oid):
    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
        cmdgen.CommunityData(community),
        cmdgen.UdpTransportTarget((host, 161)),
        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:
                return(str(val)) 
Example #5
Source File: pysnmp_3.py    From Mastering-Python-Networking-Third-Edition with MIT License 6 votes vote down vote up
def snmp_query(host, community, oid):
    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
        cmdgen.CommunityData(community),
        cmdgen.UdpTransportTarget((host, 161)),
        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:
                return(str(val)) 
Example #6
Source File: hnmp.py    From hnmp with ISC License 6 votes vote down vote up
def get(self, oid):
        """
        Get a single OID value.
        """
        snmpsecurity = self._get_snmp_security()

        try:
            engine_error, pdu_error, pdu_error_index, objects = self._cmdgen.getCmd(
                snmpsecurity,
                cmdgen.UdpTransportTarget((self.host, self.port), timeout=self.timeout,
                                          retries=self.retries),
                oid,
            )

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

        _, value = objects[0]
        value = _convert_value_to_native(value)
        return value 
Example #7
Source File: usecase_updatedescription.py    From Practical-Network-Automation-Second-Edition with MIT License 6 votes vote down vote up
def checkloopback45(ip,interface):
     loopbackpresent=False
     cmdGen = cmdgen.CommandGenerator()
     errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(
    cmdgen.CommunityData('mytest'),
    cmdgen.UdpTransportTarget((ip, 161)),
    0,25,
    '1.3.6.1.2.1.31.1.1.1.18','1.3.6.1.2.1.2.2.1.2','1.3.6.1.2.1.31.1.1.1.1'
    )
     for varBindTableRow in varBindTable:
        tval=""
        for name, val in varBindTableRow:
            if (("Loopback45" in str(val)) or ("Lo45" in str(val))):
                tval=tval+"MIB: "+str(name)+" , Interface info: "+str(val)+"\n"
                loopbackpresent=True
            
        if (loopbackpresent):
            tval=tval+"IP address of the device: "+ip
            print (tval+"\n")
            if ("test interface created" in tval):
                pushconfig(ip,"Loopback45","Mgmt loopback interface") 
Example #8
Source File: usecase_loopback.py    From Practical-Network-Automation-Second-Edition with MIT License 6 votes vote down vote up
def checkloopback45(ip,interface):
     loopbackpresent=False
     cmdGen = cmdgen.CommandGenerator()
     errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(
    cmdgen.CommunityData('mytest'),
    cmdgen.UdpTransportTarget((ip, 161)),
    0,25,
    '1.3.6.1.2.1.2.2.1.2'
    )
     for varBindTableRow in varBindTable:
        for name, val in varBindTableRow:
            if (interface in val.prettyPrint()):
                loopbackpresent=True
                break
     if loopbackpresent:
        print ("\nFor IP %s interface %s is present" % (ip,interface))
     else:
        print ("\nFor IP %s interface %s is NOT present. Pushing the config" % (ip,interface))
        pushconfig(ip,interface) 
Example #9
Source File: patator.py    From patator with GNU General Public License v2.0 6 votes vote down vote up
def execute(self, host, port=None, version='2', community='public', user='myuser', auth_key='my_password', timeout='1', retries='2'):
    if version in ('1', '2'):
      security_model = cmdgen.CommunityData('test-agent', community, 0 if version == '1' else 1)

    elif version == '3':
      security_model = cmdgen.UsmUserData(user, auth_key) # , priv_key)
      if len(auth_key) < 8:
        return self.Response('1', 'SNMPv3 requires passphrases to be at least 8 characters long')

    else:
      raise ValueError('Incorrect SNMP version %r' % version)

    with Timing() as timing:
      errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(
        security_model,
        cmdgen.UdpTransportTarget((host, int(port or 161)), timeout=int(timeout), retries=int(retries)),
        (1, 3, 6, 1, 2, 1, 1, 1, 0)
        )

    code = '%d-%d' % (errorStatus, errorIndex)
    if not errorIndication:
      mesg = '%s' % varBinds
    else:
      mesg = '%s' % errorIndication

    return self.Response(code, mesg, timing)

# }}}

# IKE {{{ 
Example #10
Source File: Bruteforce.py    From Industrial-Security-Auditing-Framework with GNU General Public License v3.0 6 votes vote down vote up
def target_function(self, running, data):
        module_verbosity = boolify(self.verbosity)
        name = threading.current_thread().name

        print_status(name, 'thread is starting...', verbose=module_verbosity)

        cmdGen = cmdgen.CommandGenerator()
        while running.is_set():
            try:
                string = data.next().strip()

                errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
                    cmdgen.CommunityData(string, mpModel=self.version - 1),
                    cmdgen.UdpTransportTarget((self.target, self.port)),
                    '1.3.6.1.2.1.1.1.0',
                )

                if errorIndication or errorStatus:
                    print_error("Target: {}:{} {}: Invalid community string - String: '{}'"
                                .format(self.target, self.port, name, string), verbose=module_verbosity)
                else:
                    if boolify(self.stop_on_success):
                        running.clear()
                    print_success("Target: {}:{} {}: Valid community string found - String: '{}'"
                                  .format(self.target, self.port, name, string), verbose=module_verbosity)
                    self.strings.append((self.target, self.port, string))

            except StopIteration:
                break

        print_status(name, 'thread is terminated.', verbose=module_verbosity) 
Example #11
Source File: snmp_helper.py    From pynet with Apache License 2.0 6 votes vote down vote up
def snmp_get_oid(a_device, oid='.1.3.6.1.2.1.1.1.0', display_errors=False):
    '''
    Retrieve the given OID

    Default OID is MIB2, sysDescr

    a_device is a tuple = (a_host, community_string, snmp_port)
    '''

    a_host, community_string, snmp_port = a_device
    snmp_target = (a_host, snmp_port)

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

    (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd(
        cmdgen.CommunityData(community_string),
        cmdgen.UdpTransportTarget(snmp_target),
        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 #12
Source File: pysnmp_3.py    From Mastering-Python-Networking-Second-Edition with MIT License 6 votes vote down vote up
def snmp_query(host, community, oid):
    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
        cmdgen.CommunityData(community),
        cmdgen.UdpTransportTarget((host, 161)),
        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:
                return(str(val)) 
Example #13
Source File: snmp.py    From natlas with GNU General Public License v2.0 5 votes vote down vote up
def get_cred(self, snmp_creds):
        for cred in snmp_creds:
            # we don't currently support anything other than SNMPv2
            if (cred['ver'] != 2):
                continue

            community = cred['community']

            cmdGen = cmdgen.CommandGenerator()
            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

                return 1

        return 0

    #
    # Get single SNMP value at OID.
    # 
Example #14
Source File: snmp.py    From natlas with GNU General Public License v2.0 5 votes vote down vote up
def get_bulk(self, oid):
        cmdGen = cmdgen.CommandGenerator()
        errIndication, errStatus, errIndex, varBindTable = cmdGen.bulkCmd(
                        cmdgen.CommunityData(self.v2_community),
                        cmdgen.UdpTransportTarget((self._ip, SNMP_PORT), timeout=30, retries=2),
                        0, 50,
                        oid,
                        lookupNames = False, lookupValues = False
        )

        if errIndication:
            print('[E] get_snmp_bulk(%s): %s' % (self.v2_community, errIndication))
        else:
            ret = []
            for r in varBindTable:
                for n, v in r:
                    n = str(n)
                    if (n.startswith(oid) == 0):
                        return ret
                    ret.append(r)
            return ret

        return None


    #
    # Lookup a value from the return table of get_bulk()
    # 
Example #15
Source File: capabilities.py    From PRET with GNU General Public License v2.0 5 votes vote down vote up
def snmp(self, host, lang):
    try:
      sys.stdout.write("Checking for SNMP support:        ")
      # query device description and supported languages
      desc, desc_oid = [], '1.3.6.1.2.1.25.3.2.1.3'    # HOST-RESOURCES-MIB → hrDeviceDescr
      pdls, pdls_oid = [], '1.3.6.1.2.1.43.15.1.1.5.1' # Printer-MIB → prtInterpreterDescription
      error, error_status, idx, binds = cmdgen.CommandGenerator().nextCmd(
        cmdgen.CommunityData('public', mpModel=0), cmdgen.UdpTransportTarget(
          (host, 161), timeout=self.timeout, retries=0), desc_oid, pdls_oid)
      # exit on error
      if error: raise Exception(error)
      if error_status: raise Exception(error_status.prettyPrint())
      # parse response
      for row in binds:
        for key, val in row:
          if desc_oid in str(key): desc.append(str(val))
          if pdls_oid in str(key): pdls.append(str(val))
      # get name of device
      model = item(desc)
      # get language support
      langs = ','.join(pdls)
      self.support = filter(None, [re.findall(re.escape(pdl), langs, re.I) for pdl in lang])
      self.set_support(model)
      output().green("found")
    except NameError:
      output().errmsg("not found", "pysnmp module not installed")
    except Exception as e:
      output().errmsg("not found", e)
  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # feedback on language support 
Example #16
Source File: patator_ext.py    From project-black with GNU General Public License v2.0 5 votes vote down vote up
def execute(self, host, port=None, version='2', community='public', user='myuser', auth_key='my_password', timeout='1', retries='2'):
    if version in ('1', '2'):
      security_model = cmdgen.CommunityData('test-agent', community, 0 if version == '1' else 1)

    elif version == '3':
      security_model = cmdgen.UsmUserData(user, auth_key) # , priv_key)
      if len(auth_key) < 8:
        return self.Response('1', 'SNMPv3 requires passphrases to be at least 8 characters long')

    else:
      raise ValueError('Incorrect SNMP version %r' % version)

    with Timing() as timing:
      errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(
        security_model,
        cmdgen.UdpTransportTarget((host, int(port or 161)), timeout=int(timeout), retries=int(retries)),
        (1,3,6,1,2,1,1,1,0)
        )

    code = '%d-%d' % (errorStatus, errorIndex)
    if not errorIndication:
      mesg = '%s' % varBinds
    else:
      mesg = '%s' % errorIndication

    return self.Response(code, mesg, timing)

# }}}

# IKE {{{ 
Example #17
Source File: snmp_bruteforce.py    From isf with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def target_function(self, running, data):
        module_verbosity = boolify(self.verbosity)
        name = threading.current_thread().name

        print_status(name, 'thread is starting...', verbose=module_verbosity)

        cmdGen = cmdgen.CommandGenerator()
        while running.is_set():
            try:
                string = data.next().strip()

                errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
                    cmdgen.CommunityData(string, mpModel=self.version - 1),
                    cmdgen.UdpTransportTarget((self.target, self.port)),
                    '1.3.6.1.2.1.1.1.0',
                )

                if errorIndication or errorStatus:
                    print_error("Target: {}:{} {}: Invalid community string - String: '{}'".format(self.target, self.port, name, string), verbose=module_verbosity)
                else:
                    if boolify(self.stop_on_success):
                        running.clear()
                    print_success("Target: {}:{} {}: Valid community string found - String: '{}'".format(self.target, self.port, name, string), verbose=module_verbosity)
                    self.strings.append((self.target, self.port, string))

            except StopIteration:
                break

        print_status(name, 'thread is terminated.', verbose=module_verbosity) 
Example #18
Source File: snmp_helper.py    From provisioning-lib with GNU General Public License v3.0 5 votes vote down vote up
def snmp_get_oid2(a_device, oid='.1.3.6.1.2.1.1.1.0', display_errors=False):
    '''
    Retrieve the given OID
    Default OID is MIB2, sysDescr
    a_device is a tuple = (a_host, community_string, snmp_port)
    '''

    a_host, community_string, snmp_port = a_device
    snmp_target = (a_host, snmp_port)

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

    (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd(
        cmdgen.CommunityData(community_string),
        cmdgen.UdpTransportTarget(snmp_target),
        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 #19
Source File: snmp_helper.py    From provisioning-lib with GNU General Public License v3.0 5 votes vote down vote up
def snmp_get_oid(a_device, oid='.1.3.6.1.2.1.1.1.0', display_errors=False):
    '''
    Retrieve the given OID
    Default OID is MIB2, sysDescr
    a_device is a tuple = (a_host, community_string, snmp_port)
    '''

    a_host, community_string, snmp_port = a_device
    snmp_target = (a_host, snmp_port)

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

    (error_detected, error_status, error_index, snmp_data) = cmd_gen.nextCmd(
        cmdgen.CommunityData(community_string),
        cmdgen.UdpTransportTarget(snmp_target),
        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 #20
Source File: snmpcustomstring.py    From PythonMiniProbe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def snmp_get(self, oid, target, snmp_type, community, port, unit):
        try:
            sys.path.append('./')
            from pysnmp.entity.rfc3413.oneliner import cmdgen
            start = time.clock()
            snmpget = cmdgen.CommandGenerator()
            error_indication, error_status, error_index, var_binding = snmpget.getCmd(
                cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((target, port)), oid)
            end = time.clock()
            delta = (end - start) * 1000
        except Exception as import_error:
            logging.error(import_error)
            raise

        channel_list = [ 
            {   
                "name": "Response Time",
                "mode": "float",
                "kind": "TimeResponse",
                "value": float(delta)
            }
        ]  
        return (
            str(var_binding[0][1]),
            channel_list
        ) 
Example #21
Source File: snmpload.py    From PythonMiniProbe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def snmp_get(self, target, community, port):
        try:
            sys.path.append('./')
            from pysnmp.entity.rfc3413.oneliner import cmdgen

            data = ['.1.3.6.1.4.1.2021.10.1.3.1','.1.3.6.1.4.1.2021.10.1.3.2','.1.3.6.1.4.1.2021.10.1.3.3'] 

            snmpget = cmdgen.CommandGenerator()
            error_indication, error_status, error_index, var_binding = snmpget.getCmd(
                cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((target, port)), *data
            )
        except Exception as import_error:
            logging.error(import_error)
            raise

        channel_list = [ 
            {   
                "name": "Load Average 1min",
                "mode": "float",
                "kind": "Custom",
                "customunit": "", 
                "value": float(var_binding[0][1])
            },  
            {   
                "name": "Load Average 5min",
                "mode": "float",
                "kind": "Custom",
                "customunit": "", 
                "value": float(var_binding[1][1])
            },  
            {   
                "name": "Load Average 10min",
                "mode": "float",
                "kind": "Custom",
                "customunit": "", 
                "value": float(var_binding[2][1])
            }
        ]
        return channel_list 
Example #22
Source File: snmptraffic.py    From PythonMiniProbe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def snmp_get(self, target, countertype, community, port, ifindex):
        if countertype == "1":
            data = ["1.3.6.1.2.1.2.2.1.10.%s" % str(ifindex), "1.3.6.1.2.1.2.2.1.16.%s" % str(ifindex)]
        else:
            data = ["1.3.6.1.2.1.31.1.1.1.6.%s" % str(ifindex), "1.3.6.1.2.1.31.1.1.1.10.%s" % str(ifindex)]
        snmpget = cmdgen.CommandGenerator()
        error_indication, error_status, error_index, var_binding = snmpget.getCmd(
            cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((target, port)), *data)
        if error_indication:
            raise Exception(error_indication)
        if countertype == "1":
            traffic_in = str(long(var_binding[0][1]))
            traffic_out = str(long(var_binding[1][1]))
            traffic_total = str(long(var_binding[0][1]) + long(var_binding[1][1]))
        else:
            traffic_in = str(long(var_binding[0][1]))
            traffic_out = str(long(var_binding[1][1]))
            traffic_total = str(long(var_binding[0][1]) + long(var_binding[1][1]))

        channellist = [
            {
                "name": "Traffic Total",
                "mode": "counter",
                "unit": "BytesBandwidth",
                "value": traffic_total
            },
            {
                "name": "Traffic In",
                "mode": "counter",
                "unit": "BytesBandwidth",
                "value": traffic_in
            },
            {
                "name": "Traffic Out",
                "mode": "counter",
                "unit": "BytesBandwidth",
                "value": traffic_out
            }
        ]
        return channellist 
Example #23
Source File: snmpcustom.py    From PythonMiniProbe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def snmp_get(self, oid, target, snmp_type, community, port, unit, multiplication=1, division=1):
        try:
            sys.path.append('./')
            from pysnmp.entity.rfc3413.oneliner import cmdgen
            snmpget = cmdgen.CommandGenerator()
            error_indication, error_status, error_index, var_binding = snmpget.getCmd(
                cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((target, port)), oid)
        except Exception as import_error:
            logging.error(import_error)
            raise

        if snmp_type == "1":
            channellist = [
                {
                    "name": "Value",
                    "mode": "integer",
                    "kind": "custom",
                    "customunit": "",
                    "value": (int(var_binding[0][1]) * int(multiplication)) / int(division)
                }
            ]
        else:
            channellist = [
                {
                    "name": "Value",
                    "mode": "counter",
                    "kind": "custom",
                    "customunit": "%s" % unit,
                    "value": (int(var_binding[0][1]) * int(multiplication)) / int(division)
                }
            ]
        return channellist 
Example #24
Source File: snmp_utlity_class.py    From warriorframework with Apache License 2.0 5 votes vote down vote up
def udptransporttarget(self):
        """
        Creates UDP transport object
        Return: UDPTransport object
        """
        return cmdgen.UdpTransportTarget((self.ipaddr, self.port),
                                         timeout=self.timeout, retries=3) 
Example #25
Source File: switch.py    From igcollect with MIT License 5 votes vote down vote up
def get_snmp_connection(args):
    """ Prepare SNMP transport agent.

        Connection over SNMP v2c and v3 is supported.
        The choice of authentication and privacy algorithms for v3 is
        arbitrary, matching what our switches can do.
    """

    if args.community:
        auth_data = CommunityData(args.community, mpModel=1)
    else:
        if args.priv_proto == 'des':
            priv_proto = usmDESPrivProtocol
        if args.priv_proto == 'aes':
            priv_proto = usmAesCfb128Protocol

        auth_data = UsmUserData(
            args.user, args.auth, args.priv,
            authProtocol=usmHMACSHAAuthProtocol,
            privProtocol=priv_proto,
        )

    transport_target = cmdgen.UdpTransportTarget((args.switch, 161))

    return {
        'auth_data': auth_data,
        'transport_target': transport_target,
    } 
Example #26
Source File: hnmp.py    From hnmp with ISC License 4 votes vote down vote up
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 str(obj_table[-1][0][0].getOid()).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 = str(name.getOid()).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 #27
Source File: hnmp.py    From hnmp with ISC License 4 votes vote down vote up
def set(self, oid, value, value_type=None):
        """
        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.
        """
        snmpsecurity = self._get_snmp_security()

        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)

        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),
                (oid, data),
            )
            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 #28
Source File: snmpprocess.py    From PythonMiniProbe with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def snmp_get(self, target, community, port, process_name):
        try:
            sys.path.append('./')
            from pysnmp.entity.rfc3413.oneliner import cmdgen
            snmpget = cmdgen.CommandGenerator()
            error_indication, error_status, error_index, var_bind_table = snmpget.bulkCmd(
                cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((target, port)), 
                0,
                25,
                '.1.3.6.1.4.1.2021.2.1.2'
            )
            
            index = -1

            for var_bind_table_row in var_bind_table:
                for name, val in var_bind_table_row:
                    if val == process_name:
                        index = name[len(name) - 1]
                        break

            if index == -1:
                raise Exception('Process not found')            
            else:
                snmpget = cmdgen.CommandGenerator()
                error_indication, error_status, error_index, var_binding = snmpget.getCmd(
                    cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((target, port)), 
                    ".1.3.6.1.4.1.2021.2.1.5.%d" % index
                )
        except Exception as import_error:
            logging.error(import_error)
            raise

        channellist = [
            {
                "name": "Process Count",
                "mode": "integer",
                "kind": "Custom",
                "customunit": "",
                "value": int(var_binding[0][1])
            }
        ]
        return channellist 
Example #29
Source File: 8 HP_IMC_Set_Interface_Descriptions.py    From PYHPEIMC with Apache License 2.0 4 votes vote down vote up
def set_snmp_single(rwstring, ip_address, ifAlias, description):
    from pysnmp.entity.rfc3413.oneliner import cmdgen
    from pysnmp.proto import rfc1902
    cmdGen = cmdgen.CommandGenerator()
    cmdGen.setCmd(
        cmdgen.CommunityData(rwstring),
        cmdgen.UdpTransportTarget((ip_address, 161)),
        (ifAlias, rfc1902.OctetString(description)))