Khi bạn đã tải xuống và cài đặt thư viện PySNMP trên hệ thống Linux/Windows/OS X của bạn, bạn sẽ có thể giải quyết nhiệm vụ SNMP rất cơ bản ngay từ lời nhắc Python của bạn - lấy một số dữ liệu từ tác nhân SNMP từ xa (bạn cần ít nhất phiên bản4.3.0 để chạy mã từ trang này). Tìm nạp biến SNMPVì vậy, chỉ cần cắt và dán mã sau ngay vào dấu nhắc Python của bạn.Mã này sẽ thực hiện hoạt động SNMP GET cho đối tượng SysDescr.0 tại một phản hồi lệnh SNMP có sẵn công khai tại demo.snmplabs.com: from pysnmp.hlapi import * iterator = getCmd( SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) ) errorIndication, errorStatus, errorIndex, varBinds = next(iterator) 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: print(' = '.join([x.prettyPrint() for x in varBind]))
Nếu mọi thứ hoạt động như bạn sẽ nhận được: ... SNMPv2-MIB::sysDescr."0" = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m >>> trên bảng điều khiển của bạn. Gửi bẫy SNMPĐể gửi một thông báo bẫy tầm thường đến máy thu thông báo được lưu trữ của chúng tôi tại demo.snmplabs.com, chỉ cần cắt và dán mã sau vào phiên Python tương tác của bạn: from pysnmp.hlapi import * iterator = sendNotification( SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'trap', NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', OctetString('my system')) ).loadMibs( 'SNMPv2-MIB' ) ) errorIndication, errorStatus, errorIndex, varBinds = next(iterator) if errorIndication: print(errorIndication)
Nếu mọi thứ hoạt động như bạn sẽ nhận được:configured to download them automatically. trên bảng điều khiển của bạn.examples and library reference pages. |