我正在与 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/