【发布时间】:2021-09-27 19:50:09
【问题描述】:
以下代码适用于其他 OID,例如主机名 (1.3.6.1.2.1.1.5.0),但是我无法提取 SNMP 社区表(snmp 允许的 ips 列表)。
我在http://www.mibdepot.com/ 中搜索了 cisco 的“社区”,并找到了 5 个 OID。所有这些都没有拉任何东西: .1.3.6.1.4.1.224.2.3.6.3.1 .1.3.6.1.4.1.224.2.3.6.1.0 .1.3.6.1.4.1.224.2.3.6.3 .1.3.6.1.4.1.224.2.3.6.4.1 .1.3.6.1.4.1.224.2.3.6.4
对此的任何指导将不胜感激。谢谢!
from pysnmp import hlapi
def get(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()):
handler = hlapi.getCmd(
engine,
credentials,
hlapi.UdpTransportTarget((target, port)),
context,
*construct_object_types(oids)
)
return fetch(handler, 1)[0]
def construct_object_types(list_of_oids):
object_types = []
for oid in list_of_oids:
object_types.append(hlapi.ObjectType(hlapi.ObjectIdentity(oid)))
return object_types
def fetch(handler, count):
result = []
for i in range(count):
try:
error_indication, error_status, error_index, var_binds = next(handler)
if not error_indication and not error_status:
items = {}
for var_bind in var_binds:
items[str(var_bind[0])] = cast(var_bind[1])
result.append(items)
else:
raise RuntimeError('Got SNMP error: {0}'.format(error_indication))
except StopIteration:
break
return result
def cast(value):
try:
return int(value)
except (ValueError, TypeError):
try:
return float(value)
except (ValueError, TypeError):
try:
return str(value)
except (ValueError, TypeError):
pass
return value
def getSNMPCommunities(ip):
try:
communities = get(ip, ['1.3.6.1.4.1.224.2.3.6.1.0'], hlapi.CommunityData('public'))
return communities.get('1.3.6.1.4.1.224.2.3.6.1.0')
except:
return None
snmpCommunities = getSNMPCommunities('10.0.0.1')
print(type(snmpCommunities))
print(snmpCommunities)
【问题讨论】: