from pysnmp.hlapi import *
# SNMP GET请求示例
def snmp_get(target, oid):
iterator = getCmd(
SnmpEngine(),
CommunityData('public'), # 社区字符串,通常为'public'
UdpTransportTarget((target, 161)), # 目标IP和端口
ContextData(),
ObjectType(ObjectIdentity(oid)) # OID对象
)
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]))
# 示例调用
snmp_get('demo.snmplabs.com', '1.3.6.1.2.1.1.1.0') # 获取系统描述信息
# SNMP WALK请求示例
def snmp_walk(target, oid):
iterator = nextCmd(
SnmpEngine(),
CommunityData('public'),
UdpTransportTarget((target, 161)),
ContextData(),
ObjectType(ObjectIdentity(oid))
)
for errorIndication, errorStatus, errorIndex, varBinds in iterator:
if errorIndication:
print(errorIndication)
break
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
break
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
# 示例调用
snmp_walk('demo.snmplabs.com', '1.3.6.1.2.1.1') # 遍历系统MIB中的对象
SNMP GET 请求:
snmp_get
函数用于发送 SNMP GET 请求,获取指定 OID 的值。CommunityData('public')
:指定了社区字符串(通常是 'public'),这是 SNMPv2c 协议中的一种认证方式。UdpTransportTarget((target, 161))
:指定了目标设备的 IP 地址和端口号(默认是 161)。ObjectType(ObjectIdentity(oid))
:指定了要查询的 OID。SNMP WALK 请求:
snmp_walk
函数用于发送 SNMP WALK 请求,遍历指定 OID 下的所有子节点。nextCmd
是一个迭代器,会返回多个结果,直到遍历完所有子节点。varBinds
可以获取每个 OID 和其对应的值。这两个函数展示了如何使用 pysnmp
库与 SNMP 设备进行交互。你可以根据需要修改目标 IP、OID 和其他参数。
上一篇:python的正则表达
下一篇:python批量重命名文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站