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

The following are 26 code examples of pysnmp.entity.rfc3413.oneliner.cmdgen.CommunityData(). 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: 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 #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: 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 #4
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 #5
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 #6
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 #7
Source File: hnmp.py    From hnmp with ISC License 6 votes vote down vote up
def _get_snmp_security(self):
        if self.version == 1:
            return cmdgen.CommunityData(self.community, mpModel=0)
        elif self.version == 3:
            authproto = AUTHPROTOCOLS.get(self.authproto, AUTHPROTOCOLS['noauth'])
            privproto = PRIVPROTOCOLS.get(self.privproto, PRIVPROTOCOLS['nopriv'])

            if len(self.authkey) == 0:
                authproto = None
                authkey = None
            else:
                authkey = self.authkey

            if len(self.privkey) == 0:
                privproto = None
                privkey = None
            else:
                privkey = self.privkey

            return cmdgen.UsmUserData(self.username, authKey=authkey, privKey=privkey,
                                      authProtocol=authproto, privProtocol=privproto)
        # Default to version 2c
        else:
            return cmdgen.CommunityData(self.community, mpModel=1) 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #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: 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 #16
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 #17
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 #18
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 #19
Source File: snmp_utlity_class.py    From warriorframework with Apache License 2.0 5 votes vote down vote up
def communitydata(self):
        """
        Creates communityData object
        for SNMP v1 and V2c
        :Return: Community data object
        """
        comdata = cmdgen.CommunityData(communityIndex=self.communityname,
                                       communityName=self.communityname,
                                       mpModel=self.mpModel)
        return comdata 
Example #20
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 #21
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 #22
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 #23
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 #24
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 #25
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))) 
Example #26
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