如何将远程文件复制/下载到本地(sftp)?

时间:2019-03-07 09:56:42

标签: python sftp paramiko

尝试将远程文件/目录复制到本地计算机,但出现错误

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: 

不确定,这是怎么了。下面是代码段

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()

这可能是什么问题?

尝试使用sftp.get(remotefile,localfile)下载时,出现错误

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: 

1 个答案:

答案 0 :(得分:0)

SFTPClient.put 上传文件。

下载文件,您需要SFTPClient.get