Pysnmp+asyncio协程

Pysnmp

PySNMP是python的第三方模块,实现了SNMP v1/v2c/v3的所有功能,使用起来非常的方便,且无需安装第三方工具就可以使用。

Pysnmp加协程,获取的效率会更高

import asyncio

import pysnmp.hlapi.asyncio as hlapi

Ana_map = {
    'numbers': lambda v: v.asNumbers(),
    'hex': lambda v: v.asOctets().hex(),
    'raw': lambda v: v,
    'bin': lambda v: v.asOctets(),
    'int': lambda v: int(v),
    'preview': lambda v: str(v),
    'ascii': lambda v: v.asOctets().decode('ascii'),
    'str': lambda v: v.asOctets().decode(v.encoding),
    'utf8': lambda v: v.asOctets().decode('utf8'),
    'gbk': lambda v: v.asOctets().decode('gbk'),
}


class SnmpScanController:

    def __init__(self, hosts, oids, Community='public', User='', authKey='', privKey='', privProtocol=hlapi.usmAesCfb128Protocol,
                 Version='v2c', pool_size=100):
        self.result = {}
        self.hosts = hosts
        self.oids = oids
        self.pool_size = pool_size
        self.Community = Community
        self.User = User
        self.authkey = authKey
        self.privKey = privKey
        self.privProtocol = privProtocol
        self.Version = Version

    async def snmp_walk(self, host, oid, format='raw'):
        result = {}
        if self.Version == 'v2c':
            UsmDate = hlapi.CommunityData(self.Community)
        elif self.Version == 'v3':
            UsmDate = hlapi.UsmUserData(self.User, authKey=self.auThkey, privKey=self.privKey,
                                        authProtocol=hlapi.usmHMACSHAAuthProtocol,
                                        privProtocol=self.privProtocol)
        iterator = await hlapi.nextCmd(hlapi.SnmpEngine(),
                                       UsmDate,
                                       hlapi.UdpTransportTarget((host, 161), timeout=10, retries=2),
                                       hlapi.ContextData(),
                                       hlapi.ObjectType(hlapi.ObjectIdentity(oid)),
                                       lookupMib=False,
                                       lexicographicMode=False)  # lexicographicMode = True时打印所有oid
        for errorIndication, errorStatus, errorIndex, varBinds in iterator:
            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
                    print(k, v)
                    k = str(k)[len(str(oid)) + 1:]
                    if format in Ana_map:
                        try:
                            result[str(k)] = Ana_map[format](v)
                        except:
                            result[str(k)] = '0x' + Ana_map['hex'](v)
        self.result[oid] = result

    async def Create_tasks(self):
        semaphore = asyncio.Semaphore(self.pool_size)
        async with semaphore:
            # 排队执行并发任务
            tasks = []
            for host in self.hosts:
                tasks += [asyncio.create_task(self.snmp_walk(host, oid, format)) for oid, format in self.oids.items()]
            await asyncio.gather(*tasks)

    def StartSNMP(self):
        loop = asyncio.get_event_loop()
        task = loop.create_task(self.Create_tasks())
        loop.run_until_complete(task)
        loop.close()


if __name__ == '__main__':
	#python在3.4之后在asyncio去掉了coroutine,过高的python版本会报错
    ips = ['192.168.200.1']
    oids = {'1.3.6.1.4.1.2011.5.2.1.15.1.3': 'str', '1.3.6.1.2.1.1.1': 'utf8'}
    #v2c方式
    snmp_cla = SnmpScanController(ips, oids, Community='public')
    snmp_cla.StartSNMP()
    print(snmp_cla.result)
    #v3方式
    snmp_cla = SnmpScanController(ips, oids,User='username', authKey='password', privKey='sharekey')
    snmp_cla.StartSNMP()
    print(snmp_cla.result)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值