如何从 Python 中的多个远程服务器读取多个文件?

How to read multiple files from multiple remote servers in Python?

我有一个 AWS ubuntu 服务器的列表,例如

ubuntu@ec2-bla-95-blablabla-23.amazonaws.com
ubuntu@ec2-bla-95-blablabla-43.amazonaws.com
ubuntu@ec2-bla-95-blablabla-24.amazonaws.com
...

在这些服务器中的每一个上,我都有一个包含可变数量文件的文件夹,每个服务器的路径都是相同的,例如 /roth/files/

我想编写一个 Python 脚本来获取这些文件的内容并在我的机器上本地合并它们。

如何获取远程服务器上这些文件的内容?

我登录这些服务器的方式是

ssh -i  path/aws.pem ubuntu@ec2-bla-95-blablabla-23.amazonaws.com

例如使用密钥

我找到了类似问题的答案here

sftp_client = ssh_client.open_sftp()
remote_file = sftp_client.open('remote_filename')
try:
    for line in remote_file:
        # process line
finally:
    remote_file.close()

但我没看到你在哪里提供服务器名称和密钥...

编辑: 作为对 Ganesh 回答的一个小修正,您需要执行以下操作来获取每个文件,否则您会收到一条错误消息,抱怨您尝试获取目录:

lobj = sftp.listdir_attr(target_folder_remote)
    for o in lobj:
        name = o.filename
        sftp.get(os.path.join(target_folder_remote, name), os.path.join(target_folder_local, name))
aws_host_list = [] # Your list here

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
dest_list = list()
for host in aws_host_list:
    client.connect(host, username=<User Name>, key_filename=<.PEM File path)
    sftp = client.open_sftp()
    lobj = sftp.listdir_attr(target_folder_remote)
    for o in lobj:
        name = o.filename
        sftp.get(os.path.join(target_folder_remote, name), os.path.join(target_folder_local, name))
        dest_list.append(os.path.join(target_folder_local, name))
    sftp.close()
    client.close()

# Then process you files
for f in dest_list:
    # Combine it