我正在尝试使用基于 PySNMP 开发人员给出的示例的脚本进行 SNMP 遍历。
我的代码看起来像这样
from pysnmp.entity.rfc3413.oneliner import cmdgen
from os.path import exists
import sys
import os
# Turn on debugging
#debug.setLogger(debug.Debug('msgproc', 'secmod'))
# Enter parameters
target_IP = raw_input('Target IP (192.168.13.100): ') or '192.168.13.100'
target_port = raw_input('Target port (161): ') or 161
target_file_name = raw_input('Target filename (.txt is added): ') + '.txt'
# Check for already existing file
path = 'walks/'
if not os.path.exists(path):
os.makedirs(path)
if exists(path+target_file_name):
sys.exit("The file '%s' already exists. Try again." % target_file_name)
else:
target_file = open(path+target_file_name, 'w+')
# Initialize counter to zero
counter = 0
# Create command generator
cmdGen = cmdgen.CommandGenerator()
# Get data
errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
cmdgen.CommunityData('public'),
cmdgen.UdpTransportTarget((target_IP, target_port)),
'1.3', # <----------------- doesn't seem perfect either
lexicographicMode=True,
maxRows=5000, # <-------------------- can't leave it out
ignoreNonIncreasingOid=True,
lookupNames=True,
lookupValues=True
)
# Print errors and values to file
if errorIndication:
print(errorIndication)
else:
# Print error messages
if errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
)
else:
# Print values
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
counter += 1
target_file.write("(%s)\t start_OID: %s\tvalue =\t%s\n" % (counter, name.prettyPrint(), val.prettyPrint()))
# Finish the operation
target_file.close()
print('Writing to %s successful. %d lines have been written' % (target_file_name, counter))
sys.exit(0)
它现在工作得很好,唯一的问题是我不能省略maxRows
参数。但是,如果我总是必须输入最大行数,我该如何让它“走到最后”呢?