示例#1
0
def _snmp_connection(connection_paramaters):
    creds = connection_paramaters['creds']
    protocol = connection_paramaters.get('protocol', 'SNMPv2c')
    if protocol == 'SNMPv1':
        data = hlapi.CommunityData(creds['community'], mpModel=0)
    elif protocol == 'SNMPv2c':
        data = hlapi.CommunityData(creds['community'], mpModel=1)
    elif protocol == 'SNMPv3':
        try:
            auth_key = creds['auth_key']
            priv_key = creds['priv_key']
        except KeyError:
            auth_key = None

        if auth_key is not None:
            data = hlapi.UsmUserData(creds['user'], auth_key, priv_key)
        else:
            data = hlapi.UsmUserData(creds['user'])

    else:
        raise ValueError('Unknown protocol "{0}"'.format(protocol))

    return (hlapi.SnmpEngine(), data,
            hlapi.UdpTransportTarget(
                (connection_paramaters['host'],
                 connection_paramaters.get('port', 161))), hlapi.ContextData())
示例#2
0
    def update_stats(self):
        self.update_netif_stats()
        more_data=__class__.get(self.target_ip,[
            '1.3.6.1.2.1.1.5.0',
            '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',
            ],hlapi.CommunityData('public'))
        
        
        #cpu usage://1.3.6.1.2.1.25.3.3[.1...4]
        cpu_usages= __class__.get_bulk(self.target_ip, [
            '1.3.6.1.2.1.25.3.3',
        ], hlapi.CommunityData('public', mpModel=1), 
            32 
        )

        
        #print(more_data)
        #print(more_data['1.3.6.1.4.1.2021.10.1.1'])
        #print(more_data['1.3.6.1.2.1.1.5.0'])
        #for k,v in more_data:
        #    print(f"{k}:{v}")
        self.hostname=more_data['1.3.6.1.2.1.1.5.0']
        self.cpuload1=more_data['1.3.6.1.4.1.2021.10.1.3.1']
        self.cpuload2=more_data['1.3.6.1.4.1.2021.10.1.3.2']
        self.cpuload3=more_data['1.3.6.1.4.1.2021.10.1.3.3']
示例#3
0
    def get_auth_data(instance):
        """
        Generate a Security Parameters object based on the instance's
        configuration.
        See http://pysnmp.sourceforge.net/docs/current/security-configuration.html
        """
        if 'community_string' in instance:
            # SNMP v1 - SNMP v2

            # See http://pysnmp.sourceforge.net/docs/current/security-configuration.html
            if int(instance.get('snmp_version', 2)) == 1:
                return hlapi.CommunityData(instance['community_string'], mpModel=0)
            return hlapi.CommunityData(instance['community_string'], mpModel=1)

        elif 'user' in instance:
            # SNMP v3
            user = instance['user']
            auth_key = None
            priv_key = None
            auth_protocol = None
            priv_protocol = None
            if 'authKey' in instance:
                auth_key = instance['authKey']
                auth_protocol = hlapi.usmHMACMD5AuthProtocol
            if 'privKey' in instance:
                priv_key = instance['privKey']
                auth_protocol = hlapi.usmHMACMD5AuthProtocol
                priv_protocol = hlapi.usmDESPrivProtocol
            if 'authProtocol' in instance:
                auth_protocol = getattr(hlapi, instance['authProtocol'])
            if 'privProtocol' in instance:
                priv_protocol = getattr(hlapi, instance['privProtocol'])
            return hlapi.UsmUserData(user, auth_key, priv_key, auth_protocol, priv_protocol)
        else:
            raise ConfigurationError('An authentication method needs to be provided')
示例#4
0
def monitor_router(router):
    ip_address = str(router[0])
    community = str(router[1])
    hostname = str(router[2])
    status = {}
    warning = []
    status.update({"Type": "Router"})
    status.update({"Host": hostname})
    status.update({"IP": ip_address}) 
    cpu = quicksnmp.get(ip_address, [OID_CISCO_CPU_LOAD], hlapi.CommunityData(community))
    ram = quicksnmp.get(ip_address, [OID_CISCO_MEMORY], hlapi.CommunityData(community))
    ramm = 90
    ramm = round(memory_percent_router(float(ram), 512.00),2)
    status.update({"CPU%": float(cpu)})
    status.update({"Memory%": round(memory_percent_router(float(ram), 512.00),2)})
    if hostname == "Akagi":
        i = quicksnmp.get(ip_address, [OID_AKAGI_IN], hlapi.CommunityData(community))
        o = quicksnmp.get(ip_address, [OID_AKAGI_OUT], hlapi.CommunityData(community))
        s = quicksnmp.get(ip_address, [OID_AKAGI_SPEED], hlapi.CommunityData(community))
        bandwidth = calculate_bandwidth(i,o,s,300)
        status.update({"Bandwidth": bandwidth})
    elif hostname == "Shoukaku":
        i = quicksnmp.get(ip_address, [OID_SHOUKAKU_IN], hlapi.CommunityData(community))
        o = quicksnmp.get(ip_address, [OID_SHOUKAKU_OUT], hlapi.CommunityData(community))
        s = quicksnmp.get(ip_address, [OID_SHOUKAKU_SPEED], hlapi.CommunityData(community))
        bandwidth = calculate_bandwidth(i,o,s,300)
        status.update({"Bandwidth": bandwidth})
    if float(cpu) >= 70.0 or ramm >= 80:
        warning.append("ip: "+ ip_address)
        warning.append("host: "+ hostname)
        warning.append("cpu: " + str(cpu))
        warning.append("memory: " + str(ram))
    return status, warning
示例#5
0
    def get_bulk(self,
                 target,
                 oids,
                 community,
                 count,
                 version=1,
                 timeout=1,
                 retries=3,
                 start_from=0,
                 port=161,
                 engine=hlapi.SnmpEngine(),
                 context=hlapi.ContextData()):
        try:
            handler = hlapi.bulkCmd(
                engine, hlapi.CommunityData(community, mpModel=version),
                hlapi.UdpTransportTarget((target, port),
                                         timeout=timeout,
                                         retries=retries), context, start_from,
                count, *self._construct_object_types(oids))
        except Exception as e:
            print('> get_bulk : ', e)
            traceback.print_exc(file=sys.stdout)
            return None

        return self._fetch(handler, count)
示例#6
0
    def _get_auth(self, write_mode=False):
        """Return the authorization data for an SNMP request.

        :param write_mode: `True` if write class SNMP command is
            executed. Default is `False`.
        :returns: Either
            :class:`pysnmp.hlapi.CommunityData`
            or :class:`pysnmp.hlapi.UsmUserData`
            object depending on SNMP version being used.
        """
        if self.version == SNMP_V3:
            return snmp.UsmUserData(
                self.user,
                authKey=self.auth_key,
                authProtocol=self.auth_proto,
                privKey=self.priv_key,
                privProtocol=self.priv_proto
            )

        else:
            mp_model = 1 if self.version == SNMP_V2C else 0
            return snmp.CommunityData(
                self.write_community if write_mode else self.read_community,
                mpModel=mp_model
            )
示例#7
0
def snmpWalk(snmpVersion, community, host, port, oid):
    generator = snmp.nextCmd(snmp.SnmpEngine(),
                             snmp.CommunityData(community,
                                                mpModel=snmpVersion),
                             snmp.UdpTransportTarget((host, port)),
                             snmp.ContextData(),
                             snmp.ObjectType(snmp.ObjectIdentity(oid)),
                             lexicographicMode=False)

    results = dict()

    for errorIndication, errorStatus, errorIndex, varBinds in generator:
        if errorIndication:
            print(errorIndication)
            continue

        if errorStatus:
            print('%s at %s', errorStatus.prettyPrint(),
                  errorIndex and varBinds[int(errorIndex) - 1][0] or '?')
            continue

        for name, value in varBinds:
            results[str(name)] = str(value)

    return results
def snmpGet(snmpVersion, community, host, port, oids):

    logging.info('New Get Query [v:%d, %s, %s, %d, %s]', snmpVersion,
                 community, host, port, oids)

    objectTypes = [snmp.ObjectType(snmp.ObjectIdentity(oid)) for oid in oids]

    errorIndication, errorStatus, errorIndex, varBinds = next(
        snmp.getCmd(snmp.SnmpEngine(),
                    snmp.CommunityData(community, mpModel=snmpVersion),
                    snmp.UdpTransportTarget((host, port)), snmp.ContextData(),
                    *objectTypes))

    if errorIndication:
        logging.error(errorIndication)
        return None

    if errorStatus:
        logging.error('%s at %s', errorStatus.prettyPrint(),
                      errorIndex and varBinds[int(errorIndex) - 1][0] or '?')
        return None

    results = [(str(name), str(value)) for name, value in varBinds]

    return dict(results)
示例#9
0
def set_oid_value(oid, value, host="localhost", port=1024):
    """Helper function to set snmp oid value of a device"""
    error_indicator, error_status, error_idx, var_binds = next(
        hlapi.setCmd(
            hlapi.SnmpEngine(),
            hlapi.CommunityData("private", mpModel=0),
            hlapi.UdpTransportTarget((host, port)),
            hlapi.ContextData(),
            hlapi.ObjectType(hlapi.ObjectIdentity(oid), value),
            lookupMib=False,
        )
    )

    if error_indicator:
        print(error_indicator)
    elif error_status:
        print(
            "%s at %s"
            % (
                error_status.prettyPrint(),
                error_idx and var_binds[int(error_idx) - 1][0] or "?",
            )
        )
    else:
        v_bind = var_binds[0]
        return v_bind[1]

    return None
示例#10
0
def snmpWalk(snmpVersion, community, host, port, oid):

    logging.info('New Walk Query [v:%d, %s, %s, %d, %s]', snmpVersion,
                 community, host, port, oid)

    generator = snmp.nextCmd(snmp.SnmpEngine(),
                             snmp.CommunityData(community,
                                                mpModel=snmpVersion),
                             snmp.UdpTransportTarget((host, port)),
                             snmp.ContextData(),
                             snmp.ObjectType(snmp.ObjectIdentity(oid)),
                             lexicographicMode=False)

    results = dict()

    for errorIndication, errorStatus, errorIndex, varBinds in generator:
        if errorIndication:
            logging.error(errorIndication)
            raise Exception('SnmpWalk ErrorIndication.')

        if errorStatus:
            logging.error(
                '%s at %s', errorStatus.prettyPrint(),
                errorIndex and varBinds[int(errorIndex) - 1][0] or '?')
            raise Exception('SnmpWalk ErrorStatus.')

        for name, value in varBinds:
            results[str(name)] = str(value)

    return results
示例#11
0
    def get(self,
            target,
            oids,
            community,
            port=161,
            version=1,
            timeout=1,
            retries=3,
            engine=hlapi.SnmpEngine(),
            context=hlapi.ContextData()):
        try:
            handler = hlapi.getCmd(
                engine, hlapi.CommunityData(community, mpModel=version),
                hlapi.UdpTransportTarget((target, port),
                                         timeout=timeout,
                                         retries=retries), context,
                *self._construct_object_types(oids))
        except Exception as e:
            print('> get : ', e)
            traceback.print_exc(file=sys.stdout)
            return -1

        fetch_value = self._fetch(handler, 1)

        if fetch_value != -1:
            return fetch_value[0]
        else:
            return fetch_value
示例#12
0
    def _get_fdb_dot1q(self):
        """Fetch the forwarding database via SNMP using the Q-BRIDGE-MIB

        Returns:
            Dict[List[str]]: ports and their values
        """
        from pysnmp import hlapi

        ports = {}

        for (errorIndication, errorStatus, errorIndex,
             varBindTable) in hlapi.bulkCmd(
                 hlapi.SnmpEngine(),
                 hlapi.CommunityData('public'),
                 hlapi.UdpTransportTarget((self.hostname, 161)),
                 hlapi.ContextData(),
                 0,
                 50,
                 hlapi.ObjectType(
                     hlapi.ObjectIdentity('Q-BRIDGE-MIB', 'dot1qTpFdbPort')),
                 lexicographicMode=False):
            if errorIndication:
                Exception("snmp error {}".format(errorIndication))
            elif errorStatus:
                Exception("snmp error {}".format(errorStatus))
            else:
                for varBinds in varBindTable:
                    key, val = varBinds
                    if not val:
                        continue
                    mac = key.getMibSymbol()[-1][1].prettyPrint()
                    interface = str(int(val))
                    ports.setdefault(interface, []).append(mac)

        return ports
示例#13
0
    def _autodetect(self):
        from pysnmp import hlapi

        for (errorIndication, errorStatus, errorIndex,
             varBindTable) in hlapi.getCmd(
                 hlapi.SnmpEngine(), hlapi.CommunityData('public'),
                 hlapi.UdpTransportTarget((self.hostname, 161)),
                 hlapi.ContextData(),
                 hlapi.ObjectType(
                     hlapi.ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))):
            if errorIndication:
                Exception("snmp error {}".format(errorIndication))
            elif errorStatus:
                Exception("snmp error {}".format(errorStatus))
            else:
                sysDescr = str(varBindTable[0][1])

        if sysDescr.startswith("HPE OfficeConnect Switch 1820 24G J9980A,"):
            self._get_fdb = self._get_fdb_dot1q
        elif sysDescr.startswith("HP 1810-24G,"):
            self._get_fdb = self._get_fdb_dot1d
        else:
            Exception("unsupported switch {}".format(sysDescr))

        self.logger.debug("autodetected switch{}: {} {}".format(
            sysDescr, self._get_ports, self._get_fdb))
示例#14
0
文件: snmp.py 项目: GypsyBud/eva3
def set(oid,
        value,
        host,
        port=161,
        community='private',
        timeout=0,
        retries=0,
        snmp_ver=2):
    try:
        for (err_i, err_st, err_idx, vals) in snmp_engine.setCmd(
                snmp_engine.SnmpEngine(),
                snmp_engine.CommunityData(community, mpModel=snmp_ver - 1),
                snmp_engine.UdpTransportTarget((host, port),
                                               timeout=timeout,
                                               retries=retries),
                snmp_engine.ContextData(),
                snmp_engine.ObjectType(snmp_engine.ObjectIdentity(oid),
                                       value)):
            if err_i or err_st:
                logging.debug('snmp error: %s' % err_i)
                return None
            else:
                return True
    except:
        log_traceback()
        return False
示例#15
0
def snmp_init(agent):
    conn = {
        'snmpEng': SnmpApi.SnmpEngine(),
        'community': SnmpApi.CommunityData(agent['community']),
        'target': SnmpApi.UdpTransportTarget((agent['host'], agent['port'])),
        'context': SnmpApi.ContextData()
    }
    return conn
示例#16
0
    def __init__(self, host, community, port=161):
        if port is None:
            port = 161

        self.engine = hlapi.SnmpEngine()
        self.transport = hlapi.UdpTransportTarget((host, port))
        self.community = hlapi.CommunityData(community, mpModel=0)
        self.context = hlapi.ContextData()
示例#17
0
def monitor_pc(pc):
    ip_address = str(pc[0])
    community = str(pc[1])
    hostname = str(pc[2])
    status = {}
    warning = []
    status.update({"Type": "PC"})
    status.update({"Host": hostname})
    status.update({"IP": ip_address})
    cpu = quicksnmp.get(ip_address, [OID_PC_LOAD], hlapi.CommunityData(community))
    used_ram = quicksnmp.get(ip_address, [OID_PC_USED_RAM], hlapi.CommunityData(community))
    total_ram = quicksnmp.get(ip_address, [OID_PC_TOTAL_RAM], hlapi.CommunityData(community))
    status.update({"CPU%": float(cpu)})
    ram = 80.0
    ram = round(memory_percent_pc(float(used_ram), float(total_ram)),2)
    status.update({"Memory%": round(memory_percent_pc(float(used_ram), float(total_ram)),2)})
    hdd = quicksnmp.get(ip_address, [OID_PC_USED_DISK], hlapi.CommunityData(community))
    status.update({"HDD%": int(hdd)})
    i = quicksnmp.get(ip_address, [OID_PC_IN], hlapi.CommunityData(community))
    o = quicksnmp.get(ip_address, [OID_PC_OUT], hlapi.CommunityData(community))
    s = quicksnmp.get(ip_address, [OID_PC_SPEED], hlapi.CommunityData(community))
    bandwidth = calculate_bandwidth(i,o,s,300)
    status.update({"Bandwidth": bandwidth})
    if float(cpu) >= 70.0 or ram >= 80 or int(hdd) >= 90:
        warning.append("ip: "+ ip_address)
        warning.append("host: "+ hostname)
        warning.append("cpu: " + str(cpu))
        warning.append("memory: " + str(ram))
        warning.append("hdd%: "+ str(hdd))
    return status, warning
示例#18
0
def find_router_type(host, port):
    oid = '.1.3.6.1.2.1.1.1.0'
    #import pysnmp.hlapi as ph
    g = ph.getCmd(
        ph.SnmpEngine(), ph.CommunityData('otauB9v1kYRO'),
        ph.UdpTransportTarget((host, port)), ph.ContextData(),
        ph.ObjectType(ph.ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
    nextg = next(g)
    print(nextg)
 def run(self):
     try:
         device_info = list()
         for value in self.oid_list["oid_list"]:
             for v, k in value.items():
                 device_info.append(k)
         return self.get(self.device_ip, device_info,
                         hlapi.CommunityData(self.snmp_community_string))
     except Exception as err:
         raise ValueError(err)
示例#20
0
    def get_auth_data(instance):
        # type: (Dict[str, Any]) -> Any
        """
        Generate a Security Parameters object based on the instance's
        configuration.
        """
        if 'community_string' in instance:
            # SNMP v1 - SNMP v2
            # See http://snmplabs.com/pysnmp/docs/api-reference.html#pysnmp.hlapi.CommunityData
            if int(instance.get('snmp_version', 2)) == 1:
                return hlapi.CommunityData(instance['community_string'],
                                           mpModel=0)
            return hlapi.CommunityData(instance['community_string'], mpModel=1)

        if 'user' in instance:
            # SNMP v3
            user = instance['user']
            auth_key = None
            priv_key = None
            auth_protocol = None
            priv_protocol = None

            if 'authKey' in instance:
                auth_key = instance['authKey']
                auth_protocol = hlapi.usmHMACMD5AuthProtocol

            if 'privKey' in instance:
                priv_key = instance['privKey']
                auth_protocol = hlapi.usmHMACMD5AuthProtocol
                priv_protocol = hlapi.usmDESPrivProtocol

            if 'authProtocol' in instance:
                auth_protocol = getattr(hlapi, instance['authProtocol'])

            if 'privProtocol' in instance:
                priv_protocol = getattr(hlapi, instance['privProtocol'])

            return hlapi.UsmUserData(user, auth_key, priv_key, auth_protocol,
                                     priv_protocol)

        raise ConfigurationError(
            'An authentication method needs to be provided')
示例#21
0
def _main():
    scriptStartTime = time.time()

    oidList = []
    oidList.append('1.3.6.1.2.1.25.2.3.1.6.1')                    #memory in use
    oidList.append('1.3.6.1.2.1.25.3.3.1.2.75')                   #vCPU-1 load
    oidList.append('1.3.6.1.2.1.25.3.3.1.2.76')                   #vCPU-2 load
    oidList.append('1.3.6.1.4.1.12325.1.200.1.3.1.0')             #state table (session count)
    oidList.append('1.3.6.1.4.1.12325.1.200.1.3.2.0')             #searhes against state table
    oidList.append('1.3.6.1.4.1.12325.1.200.1.8.2.1.7.14')        #Bytes in PASS (vtnet0)
    oidList.append('1.3.6.1.4.1.12325.1.200.1.8.2.1.8.14')        #Bytes in DENY (vtnet0)
    oidList.append('1.3.6.1.4.1.12325.1.200.1.8.2.1.9.14')        #Bytes out PASS (vtnet0)
    oidList.append('1.3.6.1.4.1.12325.1.200.1.8.2.1.10.14')       #Bytes out DENY (vtnet0)
    oidList.append('1.3.6.1.4.1.12325.1.200.1.8.2.1.11.14')       #PPS in (vtnet0)
    oidList.append('1.3.6.1.4.1.12325.1.200.1.8.2.1.13.14')       #PPS out (vtnet0)

    #FORCE AN UPDATE OF THE STALE SNMP COUNTERS
    myCmd = 'snmpget -c s3cur3d 10.1.5.1    1.3.6.1.4.1.12325.1.200.1.8.2.1.7.10   > /dev/null'
    os.system(myCmd)

    snmpDict = _snmpPoke(PFSENSEIP, oidList, hlapi.CommunityData('s3cur3d'))
    #_spitJSONoutToSplunk(hello)

    myDict = {"kNetworkDictType": 'pfsense'}

    for kOid, kValue in snmpDict.items():
        #print(kOid, ":", kOid)
        #SYSTEM LEVEL COUNTERS
        if kOid == '1.3.6.1.2.1.25.2.3.1.6.1':
            myDict.update(    {"MemInUse":    kValue} )
        if kOid == '1.3.6.1.2.1.25.3.3.1.2.75':
            myDict.update(    {"vCPU1load":    kValue} )
        if kOid == '1.3.6.1.2.1.25.3.3.1.2.76':
            myDict.update(    {"vCPU2load":    kValue} )
        if kOid == '1.3.6.1.4.1.12325.1.200.1.3.1.0':
            myDict.update(    {"stateTableSessions":    kValue} )
        if kOid == '1.3.6.1.4.1.12325.1.200.1.3.2.0':
            myDict.update(    {"searchesAgainstState":    kValue} )
        #VTNET0 (WAN) COUNTERS
        if kOid == '1.3.6.1.4.1.12325.1.200.1.8.2.1.7.14':
            myDict.update(    {"vtnet0BytesInPass":    kValue} )
        if kOid == '1.3.6.1.4.1.12325.1.200.1.8.2.1.8.14':
            myDict.update(    {"vtnet0BytesInDeny":    kValue} )
        if kOid == '1.3.6.1.4.1.12325.1.200.1.8.2.1.9.14':
            myDict.update(    {"vtnet0BytesOutPass":    kValue} )
        if kOid == '1.3.6.1.4.1.12325.1.200.1.8.2.1.10.14':
            myDict.update(    {"vtnet0BytesOutDeny":    kValue} )
        if kOid == '1.3.6.1.4.1.12325.1.200.1.8.2.1.11.14':
            myDict.update(    {"vtnet0ppsIn":    kValue} )
        if kOid == '1.3.6.1.4.1.12325.1.200.1.8.2.1.13.14':
            myDict.update(    {"vtnet0ppsOut":    kValue} )

    myDict.update(    {"ScriptRunTime_GETPFSENSESTATS.py":  time.time() - scriptStartTime} )
    _spitJSONoutToSplunk(myDict)
示例#22
0
    def __init__(self,
                 host,
                 port=161,
                 community=None,
                 v3_user=None,
                 v3_auth_proto=None,
                 v3_auth_key=None,
                 v3_crypto_proto=None,
                 v3_crypto_key=None):
        ''' Constructor

        :param host: target host, domain name or IP address, str
        :param port: target port, int
        :param community: SNMP v2c community, str
        :param v3_user: SNMP v3 username, str
        :param v3_auth_proto: SNMP v3 authorization protocol,
                              should be choosed from SnmpV3AuthProtos
        :param v3_auth_key: SNMP v3 authorization key, str
        :param v3_crypto_proto: SNMP v3 cryptography protocol,
                                should be choosed from SnmpV3CryptoProtos
        :param v3_crypto_key: SNMP v3 cryptography key, str
        '''

        self.target = (host, port)
        self.community = community
        self.v3_user = v3_user
        self.v3_auth_proto = v3_auth_proto
        self.v3_auth_key = v3_auth_key
        self.v3_crypto_proto = v3_crypto_proto
        self.v3_crypto_key = v3_crypto_key

        if community is not None:
            self.version = SnmpVersions.V2C
            self.auth_data = hlapi.CommunityData(self.community)
        else:
            self.version = SnmpVersions.V3

            if (self.v3_user is None or self.v3_auth_proto is None
                    or self.v3_crypto_proto is None):
                raise TypeError('Necessary arguments not provided')

            if self.v3_auth_proto not in SnmpV3AuthProtos:
                raise TypeError('Invalid SNMP v3 authorization protocol')

            if self.v3_crypto_proto not in SnmpV3CryptoProtos:
                raise DevError('Invalid SNMP v3 cryptography protocol')

            self.auth_data = hlapi.UsmUserData(
                self.v3_user,
                self.v3_auth_key,
                self.v3_crypto_key,
                self.v3_auth_proto,
                self.v3_crypto_proto,
            )
示例#23
0
def _make_get(address, community, *objects, port=161, mp_model=1):
    """Construct a pySNMP get command.

    Defaults to SNMPv2c and port 161.

    """
    engine = hlapi.SnmpEngine()
    community = hlapi.CommunityData(community, mpModel=mp_model)
    target = hlapi.UdpTransportTarget((address, port))
    context = hlapi.ContextData()
    return hlapi.getCmd(engine, community, target, context, *objects)
示例#24
0
def getDataGraph(request):
    if request.method == 'POST':
        device_iP = request.POST.get("ip", "")
        interface = request.POST.get("interface", "")
        old = RouterData.objects.filter(ip=ip, interface=interface).latest()
        print(device_iP, interface)
        # ///////////////////////////////////

        # device_iP = '217.139.253.32'  # by user
        # device_uptime_oid = '1.3.6.1.2.1.1.3.0'
        ifInOctets = "1.3.6.1.2.1.2.2.1.10." + interface  # in by user;
        ifOutOctets = "1.3.6.1.2.1.2.2.1.16." + interface  # out
        ifSpeed = "1.3.6.1.2.1.2.2.1.5." + interface
        # hlapi.CommunityData('know!where')
        # time_data = get(device_iP, ['1.3.6.1.2.1.1.3.0'], hlapi.CommunityData('know!where'))
        in_data = get(device_iP, [ifInOctets],
                      hlapi.CommunityData('know!where'))
        out_data = get(device_iP, [ifOutOctets],
                       hlapi.CommunityData('know!where'))
        speed_data = get(device_iP, [ifSpeed],
                         hlapi.CommunityData('know!where'))
        time.sleep(8)
        in_data1 = get(device_iP, [ifInOctets],
                       hlapi.CommunityData('know!where'))
        out_data1 = get(device_iP, [ifOutOctets],
                        hlapi.CommunityData('know!where'))
        # speed_data1 = get(device_iP, [ifSpeed], hlapi.CommunityData('know!where'))

        # Delta(in) * 8*100 /(delta_time ) * speed
        print(in_data1[ifInOctets], in_data[ifInOctets])
        print(in_data1[ifInOctets] - in_data[ifInOctets])
        print(speed_data[ifSpeed])

        bandWidthin = (in_data1[ifInOctets] - in_data[ifInOctets]
                       ) * 8 * 100 / (8 * speed_data[ifSpeed])
        bandWidthout = (out_data1[ifOutOctets] - out_data[ifOutOctets]
                        ) * 8 * 100 / (8 * speed_data[ifSpeed])
        print(bandWidthin, bandWidthout)
        # /////////////////////////////////
        return JsonResponse({'input': bandWidthin, 'output': bandWidthout})
示例#25
0
    def _get_ports(self):
        """Fetch ports and their values via SNMP

        Returns:
            Dict[Dict[]]: ports and their values
        """
        from pysnmp import hlapi

        vars = [
            (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB',
                                                   'ifIndex')), 'index'),
            (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB',
                                                   'ifDescr')), 'descr'),
            (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB',
                                                   'ifSpeed')), 'speed'),
            (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB',
                                                   'ifOperStatus')), 'status'),
            (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB',
                                                   'ifInErrors')), 'inErrors'),
            (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifHCInOctets')),
             'inOctets'),
            (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifHCOutOctets')),
             'outOctets'),
        ]
        ports = {}

        for (errorIndication, errorStatus, errorIndex,
             varBindTable) in hlapi.bulkCmd(hlapi.SnmpEngine(),
                                            hlapi.CommunityData('public'),
                                            hlapi.UdpTransportTarget(
                                                (self.hostname, 161)),
                                            hlapi.ContextData(),
                                            0,
                                            20,
                                            *[x[0] for x in vars],
                                            lexicographicMode=False):
            if errorIndication:
                Exception("snmp error {}".format(errorIndication))
            elif errorStatus:
                Exception("snmp error {}".format(errorStatus))
            else:
                port = {}
                for (key, val), (base, label) in zip(varBindTable, vars):
                    index = key.getMibSymbol()[-1][0].prettyPrint()
                    val = val.prettyPrint()
                    if label == 'status':
                        val = val.strip("'")
                    port[label] = val
                ports[port.pop('index')] = port

        return ports
示例#26
0
def snmp_walk(host, oid, format='str', strip_prefix=True, community='public'):
    res = []
    for (errorIndication, errorStatus, errorIndex, varBinds) in hlapi.nextCmd(
            hlapi.SnmpEngine(),
            hlapi.CommunityData(community),
            hlapi.UdpTransportTarget((host, 161), timeout=4.0, retries=3),
            hlapi.ContextData(),
            hlapi.ObjectType(hlapi.ObjectIdentity(oid)),
            lookupMib=False,
            lexicographicMode=False):
        if errorIndication:
            raise ConnectionError(
                f'SNMP error: "{str(errorIndication)}". Status={str(errorStatus)}'
            )
        elif errorStatus:
            raise ConnectionError(
                'errorStatus: %s at %s' %
                (errorStatus.prettyPrint(),
                 errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        else:
            for x in varBinds:
                k, v = x
                if strip_prefix:
                    k = str(k)[len(str(oid)) + 1:]
                if isinstance(v, rfc1902.Integer):
                    res.append((str(k), int(v)))
                else:
                    if format == 'numbers':
                        res.append((str(k), v.asNumbers()))
                    elif format == 'hex':
                        res.append((str(k), v.asOctets().hex()))
                    elif format == 'raw':
                        res.append((str(k), v))
                    elif format == 'bin':
                        res.append((str(k), v.asOctets()))
                    elif format == 'int':
                        res.append((str(k), int(v)))
                    elif format == 'preview':
                        res.append((str(k), str(v)))
                    elif format == 'any':
                        try:
                            res.append((str(k), v.asOctets().decode('utf-8')))
                        except UnicodeDecodeError:
                            res.append((str(k), '0x' + v.asOctets().hex()))
                    elif format == 'str':
                        res.append((str(k), v.asOctets().decode(v.encoding)))
                    else:
                        assert False, "Unknown format for walk()."
    res = {a: b for a, b in res}
    return res
示例#27
0
    def get_auth_data(cls, instance):
        '''
        Generate a Security Parameters object based on the instance's
        configuration.
        See http://pysnmp.sourceforge.net/docs/current/security-configuration.html
        '''
        if "community_string" in instance:
            # SNMP v1 - SNMP v2

            # See http://pysnmp.sourceforge.net/docs/current/security-configuration.html
            if int(instance.get("snmp_version", 2)) == 1:
                return hlapi.CommunityData(instance['community_string'],
                                           mpModel=0)
            return hlapi.CommunityData(instance['community_string'], mpModel=1)

        elif "user" in instance:
            # SNMP v3
            user = instance["user"]
            auth_key = None
            priv_key = None
            auth_protocol = None
            priv_protocol = None
            if "authKey" in instance:
                auth_key = instance["authKey"]
                auth_protocol = hlapi.usmHMACMD5AuthProtocol
            if "privKey" in instance:
                priv_key = instance["privKey"]
                auth_protocol = hlapi.usmHMACMD5AuthProtocol
                priv_protocol = hlapi.usmDESPrivProtocol
            if "authProtocol" in instance:
                auth_protocol = getattr(hlapi, instance["authProtocol"])
            if "privProtocol" in instance:
                priv_protocol = getattr(hlapi, instance["privProtocol"])
            return hlapi.UsmUserData(user, auth_key, priv_key, auth_protocol,
                                     priv_protocol)
        else:
            raise Exception("An authentication method needs to be provided")
示例#28
0
def getInterfaceData(ip, community):
    answer = (get_bulk_auto(ip, ['1.3.6.1.2.1.31.1.1.1.1', '1.3.6.1.2.1.2.2.1.10',
                                 "1.3.6.1.2.1.2.2.1.16"], hlapi.CommunityData(community), "1.3.6.1.2.1.2.1.0"))
    retlist = []
    for interface in answer:
        d1 = {}
        for key in interface.keys():
            if "1.3.6.1.2.1.31.1.1.1.1" in key:
                d1["name"] = interface[key]
            elif '1.3.6.1.2.1.2.2.1.10' in key:
                d1["txInOctets"] = interface[key]
            elif "1.3.6.1.2.1.2.2.1.16" in key:
                d1["txOutOctets"] = interface[key]
        retlist.append(d1)
    return retlist
示例#29
0
def taskSnmp(oid, host, port, readcommunity):
    # sample oids of windows snmp service for debugging
    # NoSuchObject
    # oid=".0.0.0.0.0.0.0.0"
    # TimeTicks
    # oid=".1.3.6.1.2.1.1.3.0"
    # OID
    # oid=".1.3.6.1.2.1.1.2.0"
    # integer
    # oid=".1.3.6.1.2.1.1.7.0"
    # gauge
    # oid=".1.3.6.1.2.1.2.2.1.5.1"
    # Counter32
    # oid=".1.3.6.1.2.1.2.2.1.10.1"
    # IpAddres
    # oid=".1.3.6.1.2.1.4.20.1.3.127.0.0.1"
    # OctetString
    # oid=".1.3.6.1.2.1.1.1.0"
    # OctetString with MAC addres
    # oid=".1.3.6.1.2.1.2.2.1.6.6"
    req = snmp.getCmd(snmp.SnmpEngine(), snmp.CommunityData(readcommunity),
                      snmp.UdpTransportTarget((host, port)),
                      snmp.ContextData(),
                      snmp.ObjectType(snmp.ObjectIdentity(oid)))
    reply = next(req)

    if reply[0] is None:
        # ok result example(None, 0, 0,
        # [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.3.0')),
        # TimeTicks(1245987))])
        varBind = reply[3][0]

        if oid[0] == ".":
            prefix = "."
        else:
            prefix = ""
        oidInResult = prefix + str(varBind[0])

        if oidInResult != oid:
            return ("Указан неверный OID", str(oidInResult), oid)
        else:
            value = varBind[1]
            return _snmpFormatValue(value)
    else:
        # error example (RequestTimedOut('No SNMP response received before
        # timeout',), 0, 0, [])
        raise Exception(str(reply[0]))
示例#30
0
    def __init__(self, agent_ip, agent_port, community):
        self.agent_ip = agent_ip
        self.agent_port = agent_port

        # SNMPv2 community
        self.community = community
        self.engine = hlapi.SnmpEngine()
        self.community_data = hlapi.CommunityData(self.community)
        self.transport_target = hlapi.UdpTransportTarget(
            (self.agent_ip, self.agent_port))
        self.context_data = hlapi.ContextData()

        self.snmp_basic_info = (self.engine,
                                self.community_data,
                                self.transport_target,
                                self.context_data)

        super(SNMPv2Client, self).__init__()