跳过字典列表中的服务器而不是停止代码

Skip server in dictionary list instead of stopping code

所以基本上这段代码连接到服务器并将匹配此模式的文件从一个目录下载到另一个目录。但是,如果无法访问服务器,它会停止整个过程。我想让它跳到下一个服务器。我该怎么做?

它还会下载每个包含 pc_dblatmonstat_ 的文件。虽然这是部分正确的,但我只需要那些名称类似于 pc_dblatmonstat_x_x 的文件,其中 x 替换目录中该文件的实际值。

例如我想要文件 pc_dblatmonstat_tpc01n1_scl000101018.log 而不是 pc_dblatmonstat_tpc01n1.log

这是我得到的

import os
import paramiko
import re

# 1. Create function
def get_server_files(local_path, host, port, username, password, remote_path, file_pattern):
    """Connects to host and searches for files matching file_pattern
    in remote_path. Downloads all matches to 'local_path'"""
    #Opening ssh and ftp
    ssh_con = paramiko.SSHClient()
    ssh_con.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_con.connect(host, port, username, password)
    sftp_con = ssh_con.open_sftp()

    print('Connecting to', host)

    # Finding files
    all_files_in_path = sftp_con.listdir(path=remote_path)
    r = re.compile(file_pattern)
    files = list(filter(r.match, all_files_in_path))

    #Download files
    for file in files:
        file_remote = remote_path + file
        file_local = local_path + file

        print(file_remote + ' >>> ' + file_local)

        sftp_con.get(file_remote, file_local)
        #sftp_con.put(file_local, file_remote)

    sftp_con.close()
    ssh_con.close()

# 2. list of servers
# Add new dictionary for each server to this list
list_of_servers = [
    { 'host': '192.168.1.64',
      'port': 22, 
      'username': 'pi', 
      'password': 'pi', 
      'remote_path': '/home/pi/Desktop/logs/', 
      'file_pattern': 'pc_dblatmonstat_*_'},

      { 'host': '192.168.1.65',
      'port': 22, 
      'username': 'pi', 
      'password': 'pi', 
      'remote_path': '/home/pi/Desktop/logs/',  
      'file_pattern': 'pc_dblatmonstat_*_'}
]

# You could add the local_path to the function to define individual places for the
# files that you download.
local_path = r'C:\Users\urale\Desktop\logs\'


# 3. Iterate through the list_of_servers, using the function above
for server in list_of_servers:
    get_server_files(local_path, **server)

在您的 for 循环中,您可以 try, except 无法访问服务器时的错误并跳至下一个,如下所示:

for server in list_of_servers:
    try:
        get_server_files(local_path, **server)
    except:
        continue

要解决您的第二个问题,为什么不更新 file_pattern 以指定必须有第二个 'x',如您所述:'pc_dblatmonstat_[^_]*_.*'。这部分 [^_]* 意味着您期望任意数量的非下划线字符,而模式的其余部分指定必须有另一个下划线后跟任意数量的字符。因此,只有一个下划线的文件,例如您示例中的 pc_dblatmonstat_tpc01n1.log,将不会被计算为