【问题标题】:How to copy files/directories remotely from linux to windows on AWS EC2 instance using Python?如何使用 Python 将文件/目录从 Linux 远程复制到 AWS EC2 实例上的 Windows?
【发布时间】:2019-11-06 17:58:46
【问题描述】:

我正在尝试将目录从 linux 服务器复制到 windows 机器,这两个都是使用 Python 的 AWS EC2 实例,但无法做到。

我尝试了似乎不适用于 AWS 实例的 scp 命令,还尝试在 python 中使用 paramiko 模块的 sftp 客户端,但该客户端也无法正常工作,并为 Windows 目标位置路径抛出访问错误。

localpath = 'D:/Temp'
remotepath = '/home/temp'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=HOST,port=PORT,username=USERNAME,key_filename=KEY)
sftp=ssh.open_sftp()
sftp.put(localpath,remotepath)
sftp.close()
ssh.close()

以下是错误:

Error:
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    sftp.put(localpath,remotepath)
  File "C:\Python27\lib\site-packages\paramiko\sft
    with open(localpath, "rb") as fl:
IOError: [Errno 13] Permission denied: 'D:\\Temp'

【问题讨论】:

    标签: python linux windows amazon-ec2


    【解决方案1】:

    首先,在您的 Windows 服务器上安装 putty

    然后,在你的 windows cmd 中,运行:

    pscp user@linux_ip:/path/to/file D:/path/to/destination
    

    【讨论】:

    • D:/path/to/destination本地windows路径吗?
    • 这是user@linux_ip:/path/to/file远程(EC2)路径吗?
    • 如何为pscp提供pem(ppk)文件?
    【解决方案2】:

    你可以试试我的例子:

    import os
    import paramiko
    import datetime
    
    
    def GetFileFromRemote(host_ip, host_port, host_username, host_password, remote_path, local_path):
        if not os.path.exists(local_path):
            os.makedirs(local_path)
        scp = paramiko.Transport((host_ip, host_port))
        scp.connect(username=host_username, password=host_password)
        sftp = paramiko.SFTPClient.from_transport(scp)
    
        try:
            remote_files = sftp.listdir(remote_path)
            for file in remote_files:
                local_file = local_path + file
                remote_file = remote_path + file
                sftp.get(remote_file, local_file)
        except IOError:
            return ("remote_path or local_path is not exist")
        finally:
            scp.close()
    
    
    if __name__ == '__main__':
        host_ip = '1.2.2.152'
        host_port = 22
        host_username = 'user123'
        host_password = 'password123'
        remote_path = '/home/MY/PH/'
        now_date = datetime.datetime.now().strftime('%Y%m%d')+"/"
        local_path = r"D:/CGI/" + now_date
        GetFileFromRemote(host_ip, host_port, host_username, host_password, remote_path, local_path)
    

    希望能帮到你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2020-09-17
      • 2014-11-07
      • 2016-08-25
      • 1970-01-01
      • 2021-02-10
      相关资源
      最近更新 更多