我是python的新手,所以也许有人问过类似的问题,但由于我的情况我不明白答案,很抱歉,如果这是一个愚蠢的问题。
我正在传递此snmp函数(获取或批量传递)要循环通过的ip地址列表,然后打印我请求的MIB信息。
我已经尝试了很多方法来做到这一点;不同的循环,列表理解,使用.join和.split使其成为逗号分隔的字符串,使用枚举并遍历索引,使用netaddr变量等,通常会导致某种类型的错误。我试图将每个IP地址作为字符串传递给该函数,该函数要求输入字符串。如果我尝试使用“ for a in a:”循环直接遍历列表,则会遇到类似的错误。
当我为每个字符串打印类型时,它说它是一个字符串。为什么这不起作用,推荐的方法是什么?
在这种特定情况下,我遇到以下错误:
如果snmp批量:
TYPEError:int()参数必须是字符串,类似字节的对象或数字,而不是'ObjectType'
如果snmp得到:
TYPEError:“ int”对象不可下标
下面列出的代码和结果:
from pysnmp.hlapi import *
from nmapPoller import a
def snmpquery(hostip):
snmp_iter = bulkCmd(SnmpEngine(),
CommunityData('public'),
UdpTransportTarget((hostip, 161)),
ContextData(),
1,
255,
ObjectType(ObjectIdentity('IF-MIB','ifOperStatus')),
lexicographicMode=True)
for errorIndication, errorStatus, errorIndex, varBinds in snmp_iter:
# Check for errors and print out results
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]))
print(a)
result: ['10.200.100.1', '10.200.100.8']
print(type(a))
result: <class 'list'>
for i, x in enumerate(a):
host = a[i]
str(host) this can be excluded I believe
print(host)
result: 10.200.100.1
print(type(host))
result: <class 'str'>
#snmpquery(host) <-- Error results from running function
User9876通过在上面添加maxrepetitions来解决我的问题。
答案 0 :(得分:2)
根据these docs,您正在调用的函数定义为:
pysnmp.hlapi.bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options)
maxRepetitions(int)
但是对于maxRepetitions
参数,您传递的是ObjectType()
而不是整数。我认为ObjectType()
应该是*varBinds
之一,我想您错过了maxRepetitions
参数。
在您的代码中:
snmp_iter = bulkCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget((hostip, 161)), ContextData(), 1,
我认为您缺少应该在此处使用的maxRepetitions
参数...
ObjectType(ObjectIdentity('IF-MIB','ifOperStatus')), lexicographicMode=True)