python - 使用 pexpect 和大量地址进行循环

标签 python for-loop pexpect

我正在与 pexpect 合作。目标是按顺序连接到文本文件中的地址列表,连接后执行操作,注销并转到下一个地址。

我的基本功能运行得很好。这是令人讨厌的错误。如果客户端没有响应,它就会崩溃。我使用了“try”,但如果出现异常,则会中断 for 循环,并且不会继续下一个地址。

尝试每一项、做一些事情的最佳方法是什么,如果它失败了......在日志文件中做一个记录,然后继续下一个,直到我们到达列表的末尾。这是我当前的:

i = open('addresses.txt')
addresses = i.readlines()
i.close()

for address in addresses:
  c = pexpect.spawn('ssh -o StrictHostKeyChecking=no %s@%s' % (user, address))
  c.logfile = sys.stdout
  c.timeout = 5
  c.expect('something')
  c.sendline('do something')
   etc etc.

最佳答案

收集特定的和预期的错误

errors = []
for address in addresses:
    try:
       c = pexpect.spawn('ssh -o StrictHostKeyChecking=no %s@%s' % (user, address))
       c.logfile = sys.stdout
       c.timeout = 5
       c.expect('something')
       c.sendline('do something')
   except Exception as e:   # replace with the type of exception you expect
       errors.append(dict(address=address, exception=e))

这不应破坏 for 循环,完成后您可以读取错误,

if errors:
    # report them, do something etc
    # the errors are informative, with address and exception objects in the dict

关于python - 使用 pexpect 和大量地址进行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31089243/

相关文章:

python - Beautiful Soup Select 与 Find_all 数据类型

python - 如果实例记录在类字典中,__del__ 不起作用

java - for 语句不循环 - android

python - 无法使用 cygwin 运行 pexect

python - Pexpect,运行 ssh-copy-id 在尝试生成第二个进程时挂起

python - 让 RandomForestClassifier 在训练期间确定选择一个变量

python - 如何在 Python 中防止属性初始化为某些值

javascript 使用 for 循环创建编号行

java - 用数字打印倒三角形 - Java

python - 关于 python 中 pexpect 的问题