2017-10-09 118 views
0

我有一個代碼,其中im循環通過主機列表和附加連接到連接列表,如果有連接錯誤,我想跳過它並繼續與主機列表中的下一個主機。異常後如何繼續循環?

繼承人什麼,我現在有:

def do_connect(self): 
    """Connect to all hosts in the hosts list""" 
    for host in self.hosts: 
     try: 
      client = paramiko.SSHClient() 
      client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
      client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2) 
     except: 
      pass 
      #client.connect(host['ip'], port=int(host['port']), username=host['user'], password=host['passwd']) 

     finally: 
      if paramiko.SSHException(): 
       pass 
      else: 
       self.connections.append(client) 

這並不正常工作,如果連接失敗,它只是一次又一次的循環,在同一臺主機永遠,直到它建立連接,我怎麼解決這個問題?

+1

使用['continue'](https://docs.python.org/3/reference/simple_stmts.html#continue)。 – Mark

+0

我不明白爲什麼它會永遠循環同一個主機? – Sraw

+0

我沒有看到任何代碼再次循環相同的主機 – Sanket

回答

1

你自己的答案還是錯了不少分...

import logging 
logger = logging.getLogger(__name__) 

def do_connect(self): 
    """Connect to all hosts in the hosts list""" 
    for host in self.hosts: 
     # this one has to go outside the try/except block 
     # else `client` might not be defined. 
     client = paramiko.SSHClient() 
     try: 
      client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
      client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2) 

     # you only want to catch specific exceptions here 
     except paramiko.SSHException as e: 
      # this will log the full error message and traceback 
      logger.exception("failed to connect to %(ip)s:%(port)s (user %(user)s)", host) 

      continue 
     # here you want a `else` clause not a `finally` 
     # (`finally` is _always_ executed) 
     else: 
      self.connections.append(client) 
+0

我得到超時錯誤以及由於2秒超時計時器,所以不得不導入socket.timeout讓它正常工作,否則這個工程。接受的答案 – Nanoni

0

好吧,得到它的工作,我需要添加繼續,由馬克提及,還有以前,如果終於內部檢查總是返回true,所以這是固定的。

這裏是固定的代碼,這並不增加連接失敗後,通常繼續循環:

def do_connect(self): 
    """Connect to all hosts in the hosts list""" 
    for host in self.hosts: 
     try: 
      client = paramiko.SSHClient() 
      client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
      client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2) 
     except: 
      continue 
      #client.connect(host['ip'], port=int(host['port']), username=host['user'], password=host['passwd']) 

     finally: 
      if client._agent is None: 
       pass 
      else: 
       self.connections.append(client) 
+0

您應該只捕獲特定的異常(您的案例中的連接錯誤),並且始終記錄它們(以便您可以檢查是否發生了錯誤)。你也希望把客戶端實例放在try/except塊之外(否則,如果它在第一個主機上失敗,客戶端將不會被定義,並且你會在finally塊中得到一個NameError),並且fwiw this不應該是'finally'塊,而是'else'塊(如果沒有發生異常,它將只會被執行)。 –