2019年8月20日 星期二

Python pysnmp 簡介

之前在開發Java監控Server需要用到snmp套件是使用snmp4j
在.net(C#)是使用SNMPSharpNet
今天則是記錄Python上找了一下比較方便的套件pysnmp
官方網站如下:http://snmplabs.com/pysnmp/index.html

基本的snmpget、snmpset 操作說明如下

###套件安裝
pip install pysnmp

###把snmpget包裝成一個方法呼叫

from pysnmp.hlapi import *
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto import rfc1902

ip = '127.0.0.1'
oid = "1.3.6.1.2.1.2.2.1.8.1"
result = snmpget(ip,oid)

def snmpget(ip,oid):
    errorIndication, errorStatus, errorIndex, varBinds = next(
        getCmd(SnmpEngine(),
            CommunityData('private'),
            UdpTransportTarget((ip, 161)),
            ContextData(),
            ObjectType(ObjectIdentity(oid)))
    )

    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        for varBind in varBinds:
            return(str(varBind).split('=')[1])


###snmpset用法,此方法為一次設定兩個OID

from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto import rfc1902

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd(
 cmdgen.CommunityData('private', mpModel=0),
 cmdgen.UdpTransportTarget(127.0.0.1, 161)),
 ('.1.3.6.1.2.1.0.1.1', rfc1902.Integer(1)),
 ('.1.3.6.1.2.1.0.1.2, rfc1902.Integer(1))
)


若有問題都歡迎討論,謝謝。

沒有留言:

張貼留言

CentOS Python 3.7 安裝方式

有些開發的程式在python 3.8的檔案套件不相容,例如pymssql,等。 所以如果不建置虛擬環境的話才特意安裝3.7版本的python 安裝流程如下 # 先進行yum套件的update yum update -y # 安裝相依性套件 yum install gcc o...