Skip to main content
 首页 » 编程设计

python之For 循环使用 pexpect 和大量地址来处理

2024年10月24日16xing901022

我正在使用 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