简体   繁体   中英

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.

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.

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.

Then, in your windows cmd, run:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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