使用Python提取交换机SNMP社区列表



下面的代码适用于其他oid,如主机名(1.3.6.1.2.1.1.5.0),但是我在拉SNMP社区表(SNMP允许的ip列表)时遇到麻烦。

我搜索了"社区"在http://www.mibdepot.com/找到了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)

这是不可能的,因为SNMP只读不应该访问这些信息。

我想到的解决方案是通过SSH登录并读取标准输出。

最新更新