【问题标题】:Python Pysnmp Loop always returns must be string type error, even though the variable is a stringPython Pysnmp 循环总是返回必须是字符串类型的错误,即使变量是字符串
【发布时间】: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 解决了我的问题,添加到上面。

【问题讨论】:

    标签: python pysnmp


    【解决方案1】:

    根据these docs,你调用的函数定义为:

    pysnmp.hlapi.bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options)

    最大重复次数(整数)

    但是对于 maxRepetitions 参数,您传递的是 ObjectType() 而不是 int。我认为ObjectType() 应该是*varBinds 之一,我认为您错过了maxRepetitions 参数。

    在您的代码中:

    snmp_iter = bulkCmd(SnmpEngine(), 社区数据('公共'), UdpTransportTarget((hostip, 161)), 上下文数据(), 1、

    我认为您缺少应该放在此处的 maxRepetitions 参数...

    ObjectType(ObjectIdentity('IF-MIB','ifOperStatus')), 字典模式=真)

    【讨论】:

    • 非常感谢,添加 maxrepetitions 解决了我的问题,相关代码在上面。
    猜你喜欢
    • 2018-07-24
    • 2018-04-24
    • 2016-11-13
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多