【发布时间】:2018-09-29 19:11:31
【问题描述】:
我是 python 新手,所以可能有人问了类似的问题,但我不明白答案,因为它与我的情况有关,如果这是一个愚蠢的问题,对不起。
我正在传递这个 snmp 函数,get 或 bulk,一个要循环的 ip 地址列表,然后打印我请求的 MIB 信息。
我尝试了很多方法;不同的循环,列表理解,使用 .join 和 .split 使它们成为逗号分隔的字符串,使用枚举和循环索引,使用 netaddr 变量等,通常会导致某种类型的错误。我试图将每个 ip 地址作为字符串传递给函数,该函数要求一个字符串。如果我尝试使用“for a in a:”循环直接遍历列表,我最终会遇到类似的错误。
当我打印每个字符串的类型时,它说它是一个字符串。为什么这不起作用?推荐的方法是什么?
在这种特定情况下,我收到以下错误:
如果 snmp 批量:
TYPEError: int () argument must be a string, a bytes-like object or a number, not '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 解决了我的问题,添加到上面。
【问题讨论】: