Python封裝SNMP調(diào)用接口的示例代碼
PySNMP 是一個(gè)純粹用Python實(shí)現(xiàn)的SNMP,用PySNMP的最抽象的API為One-line Applications,其中有兩類API:同步的和非同步的,都在模塊pysnmp.entity.rfc3413.oneliner.cmdgen 中實(shí)現(xiàn),如下是Get方式與Walk方式的基本實(shí)現(xiàn).
首先需要在系統(tǒng)中安裝SNMP客戶端,對(duì)于Linux平臺(tái)來(lái)說(shuō)只需要執(zhí)行如下配置過(guò)程即可.
[root@localhost ~]# yum install -y net-snmp [root@localhost ~]# cat /etc/snmp/snmpd.conf |grep -vE "^#|^$" com2sec notConfigUser default public group notConfigGroup v1 notConfigUser group notConfigGroup v2c notConfigUser view systemview included .1 view systemview included .1 access notConfigGroup "" any noauth exact systemview none none [root@localhost ~]# systemctl restart snmpd [root@localhost ~]# systemctl enable snmpd
如果是Windows系統(tǒng)則需要在客戶機(jī)服務(wù)列表,開啟SNMP支持,并設(shè)置好一個(gè)團(tuán)體名稱,如下圖。
當(dāng)我們配置好客戶端后,服務(wù)端就客戶獲取數(shù)據(jù)了,我們以一個(gè)OID序號(hào)為例,我們查詢特定序號(hào)對(duì)應(yīng)的名稱,然后將其記錄下來(lái),例如下面這樣。
C:\Users\admin> snmpwalk -v 2c -c public 192.168.1.101 .1.3.6.1.2.1.25.2.2
HOST-RESOURCES-MIB::hrMemorySize.0 = INTEGER: 2096632 KBytes
首先我們不使用PySNMP模塊直接開線程調(diào)用看看,該代碼如下所示.
import os,re,time # 通過(guò)SNMP收集主機(jī)CPU利用率: 通過(guò)SNMP協(xié)議,收集目標(biāo)主機(jī)的CPU利用率(百分比),并返回JSON字符串. def Get_CPU_Info(addr): try: Head = ["HostName","CoreLoad","CpuUser","CpuSystem","CpuIdle"] CPU = [] ret = os.popen("snmpwalk -v 2c -c nmap " + addr + " .1.3.6.1.2.1.1.5") CPU.append(ret.read().split(":")[3].strip()) ret = os.popen("snmpwalk -v 2c -c nmap " + addr + " .1.3.6.1.2.1.25.3.3.1.2") CPU.append(ret.read().split(":")[3].strip()) for i in [9,10,11]: ret = os.popen("snmpwalk -v 2c -c nmap " + addr + " 1.3.6.1.4.1.2021.11.{}.0".format(i)) ret = ret.read() Info = ret.split(":")[3].strip() CPU.append(Info) return dict(zip(Head,CPU)) except Exception: return 0 # 通過(guò)SNMP獲取系統(tǒng)CPU負(fù)載信息: 分別獲取到系統(tǒng)的1,5,15分鐘的負(fù)載信息,并返回JSON格式. def Get_Load_Info(addr): try: Head = ["HostName","Load1","Load5","Load15"] SysLoad = [] ret = os.popen("snmpwalk -v 2c -c nmap " + addr + " .1.3.6.1.2.1.1.5") SysLoad.append(ret.read().split(":")[3].strip()) ret = os.popen("snmpwalk -v 2c -c nmap " + addr + " .1.3.6.1.4.1.2021.10.1.3") load = list(re.sub(".*STRING: ", "", ret.read()).split("\n")) SysLoad.append(load[0]) SysLoad.append(load[1]) SysLoad.append(load[2]) return dict(zip(Head,SysLoad)) except Exception: return 0 # 通過(guò)SNMP獲取系統(tǒng)內(nèi)存占用: 內(nèi)存利用率,獲取到之后,將其轉(zhuǎn)化為字典格式保存。 def Get_Mem_Info(addr): try: Head = ["HostName","memTotalSwap","memAvailSwap","memTotalReal","memTotalFree"] SysMem = [] ret = os.popen("snmpwalk -v 2c -c nmap " + addr + " .1.3.6.1.2.1.1.5") SysMem.append(ret.read().split(":")[3].strip()) ret = os.popen("snmpwalk -v 2c -c nmap " + addr + " .1.3.6.1.4.1.2021.4") mem = ret.read().split("\n") for i in [2,3,4,6]: SysMem.append(re.sub(".*INTEGER: ","",mem[i]).split(" ")[0]) return dict(zip(Head,SysMem)) except Exception: return 0 # 通過(guò)SNMP獲取系統(tǒng)磁盤數(shù)據(jù): 這個(gè)案例并不完整,我只寫了一點(diǎn),后面有個(gè)問(wèn)題一直沒(méi)有解決. def Get_Disk_Info(addr): try: dic = {} list = [] ret = os.popen("snmpwalk -v 2c -c nmap " + addr + " HOST-RESOURCES-MIB::hrStorageDescr") DiskName = ret.read().split("\n") ret =os.popen("snmpwalk -v 2c -c nmap " + addr + " HOST-RESOURCES-MIB::hrStorageUsed") DiskUsed = ret.read().split("\n") ret = os.popen("snmpwalk -v 2c -c nmap " + addr + " HOST-RESOURCES-MIB::hrStorageSize") DiskSize = ret.read().split("\n") for i in range(1,len(DiskName) - 7): dic["Name"]= DiskName[i + 5].split(":")[3] dic["Used"]= DiskUsed[i + 5].split(":")[3] dic["Size"]= DiskSize[i + 5].split(":")[3] list.append(dic) return list except Exception: return 0 if __name__ == '__main__': for i in range(100): dic = Get_CPU_Info("192.168.1.20") print(dic) time.sleep(1)
我們使用pysnmp模塊來(lái)做,安裝pysnmp很簡(jiǎn)單,執(zhí)行命令pip install pysnmp
即可,安裝后使用以下代碼執(zhí)行即可獲取到目標(biāo)數(shù)據(jù),獲取方式分為兩種一種為Get另一種為Walk.
from pysnmp.hlapi import * import os,sys class NetSNMP(): def __init__(self,address,region): self.region = region self.address = address # 獲取指定數(shù)據(jù)的方法 def GetNumber(self,oid,sub_oid,sub_id): iterator = getCmd(SnmpEngine(), CommunityData(self.region), UdpTransportTarget((self.address, 161)), ContextData(), ObjectType(ObjectIdentity(oid, sub_oid, sub_id))) errorIndication, errorStatus, errorIndex, varBinds = next(iterator) if errorIndication: return False else: if errorStatus: return False else: for varBind in varBinds: return [x.prettyPrint() for x in varBind] # 使用Walk拉取數(shù)據(jù) def WalkNumber(self, oid): res = [] for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData(self.region),UdpTransportTarget((self.address, 161)),ContextData(), ObjectType(ObjectIdentity(oid)).addMibSource( './site-packages/pysnmp/smi/mibs','pysnmp_mibs'),lexicographicMode=False): if errorIndication: print(errorIndication, file=sys.stderr) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'), file=sys.stderr) break else: for varBind in varBinds: res.append(str(varBind)) return res if __name__ == "__main__": # 初始化 ptr = NetSNMP("192.168.81.130","public") # 使用GET方式獲取OID數(shù)據(jù) ret = ptr.GetNumber("HOST-RESOURCES-MIB","hrMemorySize",0) print("類型: {} --> 返回結(jié)果: {} --> 解析: {}".format(type(ret),ret,ret[1])) # 使用Walk方式獲取OID數(shù)據(jù) ret = ptr.WalkNumber(".1.3.6.1.2.1.2.2.1.6") for each in ret: mac = each.split("=")[1] if len(mac) > 1: print("網(wǎng)卡接口: {}".format(mac))
以上就是Python封裝SNMP調(diào)用接口的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Python SNMP調(diào)用接口的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python?數(shù)據(jù)分析教程探索性數(shù)據(jù)分析
這篇文章主要介紹了Python?數(shù)據(jù)分析教程探索性數(shù)據(jù)分析,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08keras分類模型中的輸入數(shù)據(jù)與標(biāo)簽的維度實(shí)例
這篇文章主要介紹了keras分類模型中的輸入數(shù)據(jù)與標(biāo)簽的維度實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07快速解決pyqt5窗體關(guān)閉后子線程不同時(shí)退出的問(wèn)題
今天小編就為大家分享一篇快速解決pyqt5窗體關(guān)閉后子線程不同時(shí)退出的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06Python3如何日志同時(shí)輸出到控制臺(tái)和文件
這篇文章主要介紹了Python3如何日志同時(shí)輸出到控制臺(tái)和文件問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11Python中集合的創(chuàng)建及常用函數(shù)的使用詳解
這篇文章主要為大家詳細(xì)介紹了Python中集合的創(chuàng)建、使用和遍歷,集合常見的操作函數(shù),集合與列表,元組,字典的嵌套,感興趣的小伙伴可以了解一下2022-06-06TensorFlow卷積神經(jīng)網(wǎng)絡(luò)AlexNet實(shí)現(xiàn)示例詳解
這篇文章主要為大家介紹了TensorFlow卷積神經(jīng)網(wǎng)絡(luò)AlexNet實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11