【问题标题】:How to iterate through your python script even if one statement failed?即使一个语句失败,如何遍历你的 python 脚本?
【发布时间】:2019-09-28 06:37:18
【问题描述】:

我正在尝试使用 paramiko 在 cisco 框列表上执行某些命令,如果命令无法在一个框上执行,则它无法在代码中进行并退出。我希望代码继续运行,即使它无法登录一台设备或无法执行任何操作

这会读取一个 ts.txt 文件,其中包含要登录和执行一些命令的设备列表,

with open("ts.txt") as f:
    x= [l.strip() for l in f]

    for line in x:

            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh_client.connect(hostname=line,username=username,password=password)

            print "Successful connection", line

            remote_connection = ssh_client.invoke_shell()


            remote_connection.send("sh ver")
            remote_connection.send("\n")

错误:

File "/usr/lib/python2.7/site-packages/paramiko-2.4.0-py2.7.egg/paramiko/client.py", line 714, in _auth

如果它无法登录一个设备,它会退出,我希望它继续列表的其余部分。

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 阅读捕获异常

标签: python ssh automation paramiko


【解决方案1】:

来自 python 文档的 try/except 块:

首先,执行 try 子句(try 和 except 关键字之间的语句)。 如果没有发生异常,则跳过 except 子句并完成 try 语句的执行。 如果在 try 子句执行期间发生异常,则跳过该子句的其余部分。然后如果它的类型与以 except 关键字命名的异常匹配,则执行 except 子句,然后在 try 语句之后继续执行。 如果发生与 except 子句中指定的异常不匹配的异常,则将其传递给外部 try 语句;如果未找到任何处理程序,则为未处理的异常,执行将停止并显示如上所示的消息。

for line in x:
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=line,username=username,password=password)

        print "Successful connection", line
        remote_connection = ssh_client.invoke_shell()
        remote_connection.send("sh ver")
        remote_connection.send("\n")
    except Exception as e:
        print "Error: " + e

请注意,except Exception as e 将捕获所有异常,而不仅仅是您想要的。

【讨论】:

  • @user12132912 如果这个案例完成了,如果您单击左侧的小勾号,在赞成/反对票下方,我将不胜感激。只是将此问题标记为已回答:D
  • 我怎样才能有 2 个 try 语句,我希望脚本尝试一个用户名/密码,如果失败,请尝试另一组 username2/pwd2,执行某些显示命令,最后如果两个密码都失败了
猜你喜欢
  • 2020-05-02
  • 2022-06-18
  • 1970-01-01
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 2016-06-30
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多