简体   繁体   English

如何使用 Python 在 AWS EC2 实例上将文件/目录从 linux 远程复制到 windows?

[英]How to copy files/directories remotely from linux to windows on AWS EC2 instance using Python?

I am trying to copy directories from linux server to windows machine where both of these are AWS EC2 instances using Python but couldn't do that.我正在尝试将目录从 linux 服务器复制到 windows 机器,这两个机器都是使用 Python 的 AWS EC2 实例,但不能这样做。

I tried scp command which seems not working on AWS instances, also tried using sftp client of paramiko module in python which is alos not working and throwing access error for windows destination location path.我尝试了似乎无法在 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()

Following is the error:以下是错误:

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'

First, install putty on your windows server.首先,在您的 windows 服务器上安装putty

Then, in your windows cmd, run:然后,在您的 windows cmd 中,运行:

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

You can try my example:你可以试试我的例子:

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)

Hope to help you.希望能帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM