我正在尝试创建一个测试程序,该程序将登录 Cisco ASA 防火墙并收集一些数据。 我遇到了挑战。有些防火墙是单上下文的,有些是多上下文的,但是通过管理 IP 地址连接到所有防火墙。一旦连接,就会有一个命令“changeto system”,它只会在多上下文防火墙上成功。我正在考虑使用 try-except-else ....
conn = ConnectHandler(device_type= "cisco_asa", ip=host[1], username=u[host[3]], password=p[host[3]], secret=p[host[3]])
print(conn.find_prompt())
try:
output4 = conn.send_command(cmd_system)
except:
# not a multi-context firewall
for cmd in cmd_list_asa:
CONTEXT_OUTPUT = open(chgnr + '__' + host[0] + '_' + d[cmd]+ '_' + testtype , "a")
info = ("running .... " + host[0] + "......." + cmd)
runcommand(info, cmd, CONTEXT_OUTPUT)
CONTEXT_OUTPUT.close()
else:
#multi-context firewall
#collect SYSTEM context data
for cmd in cmd_list_asa:
CONTEXT_OUTPUT = open(chgnr + '__' + host[0] + '_system_' + d[cmd]+ '_' + testtype , "a")
info = ("running .... " + host[0] + "_system......." + cmd)
runcommand(info, cmd, CONTEXT_OUTPUT)
CONTEXT_OUTPUT.close()
#create context list and collect data
output3 = conn.send_command(cmd_contextlist)
list = re.findall("\"(.*?)\"",output3)
for fw in list:
cmd_change = ("changeto context " + fw)
output = conn.send_command(cmd_change)
for cmd in cmd_list_asa:
CONTEXT_OUTPUT = open(chgnr + '__' + host[0] + '_' + fw + '__' + d[cmd]+ '_' + testtype , "a")
info = ("running .... " + host[0] + "_" + fw + "......." + cmd)
runcommand(info, cmd, CONTEXT_OUTPUT)
CONTEXT_OUTPUT.close()
CONTEXT_OUTPUT 只是一种动态生成文件名的奇特方式。 测试类型来区分多次运行以及最后所有runcommand发送命令...conn.send_command(cmd)。
按照我的预期,如果 output4 命令失败,应该执行 except 部分,如果成功则应该跳转到 else 部分,但显然即使那些不是多上下文的防火墙也会通过 else 部分并跳过 except。
答案 0 :(得分:1)
在与我的同事交谈后,我意识到了我的错误。 Try-expect 用于 Python 错误处理。当命令失败时,它仍然返回一个输出
...admin> changeto system
^
ERROR: % Invalid input detected at '^' marker.
ERROR: Command authorization failed
...必须对输出进行评估,因此它应该是 if-else,而不是 try-expect-else...
....
output4 = conn.send_command(cmd_system)
if "ERROR" in output4:
# not a multi-context firewall
for cmd in cmd_list_asa:
CONTEXT_OUTPUT = open(chgnr + '__' + host[0] + '_' + d[cmd]+ '_' + testtype , "a")
info = ("running .... " + host[0] + "......." + cmd)
runcommand(info, cmd, CONTEXT_OUTPUT)
CONTEXT_OUTPUT.close()
else:
#multi-context firewall
#collect SYSTEM context data
for cmd in cmd_list_asa:
....