简体   繁体   中英

How to copy/download remote files to local (sftp)?

Trying to copy the remote files/directories to local machine, but getting error

Traceback (most recent call last):
  File "test_ssh.py", line 23, in <module>
    sftp_client.put(str(os.path.join(remote_dir,file)),os.path.join(local_dir, file))
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/paramiko/sftp_client.py", line 757, in put
    file_size = os.stat(localpath).st_size
OSError: [Errno 2] No such file or directory: 

Not sure, what is wrong here. Below is the snippet

import paramiko
import os
import stat


remote_host = "10.10.10.10"
username = "user"
key_filename = "/path/to/key_filename"
port = 22

remote_path = "/remote/path/location"

latest_folder_name = "abc_123456"
local_dir = os.path.join(os.getcwd(),latest_folder_name)
remote_dir = os.path.join(remote_path, latest_folder_name)


ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_host, username=username, key_filename=key_filename, port=port)
sftp = ssh.open_sftp()

for file in sftp.listdir(remote_dir):
    if stat.S_ISREG(sftp.stat(os.path.join(remote_dir, file)).st_mode):
        print "FILE '{}'".format(file)
        sftp.put(os.path.join(remote_dir,file),os.path.join(local_dir, file))
    else:
        print "DIRECTORY {}".format(file)
sftp.close()

What could be wrong here ?

when tried to download with sftp.get(remotefile,localfile) , error

Traceback (most recent call last):
  File "test_ssh.py", line 23, in <module>
    sftp.get(os.path.join(remote_dir,file),os.path.join(local_dir, file))
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/paramiko/sftp_client.py", line 801, in get
    with open(localpath, "wb") as fl:
IOError: [Errno 2] No such file or directory: 

SFTPClient.put uploads a file.

To download a file, you want SFTPClient.get .

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