将文件从SFTP服务器下载到本地目录

时间:2019-05-29 05:54:47

标签: python-3.x pysftp

我得到了一个代码,可以使用python将文件从远程目录下载到本地目录。我想要一个可以将单个文件从远程目录下载到本地文件夹的代码。请帮助我修改此代码。欢迎所有建议。 我测试了此代码,但是它将远程目录的所有内容下载到本地目录,但是我想要一个可以将单个文件从远程目录下载到本地目录的代码。我正在使用SFTP服务器

我得到的代码:(基于Python pysftp get_r from Linux works fine on Linux but not on Windows

import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None    
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:     
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)

1 个答案:

答案 0 :(得分:0)

import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None    
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, remotefile, localdir, preserve_mtime=False):
    remotepath = remotedir + "/" + remotefile
    localpath = os.path.join(localdir, remotefile)
     mode = sftp.stat(remotepath).st_mode
     if S_ISDIR(mode):
          try:
              os.mkdir(localpath,mode=777)
          except OSError:     
              pass
          get_r_portable(sftp, remotepath, localpath, preserve_mtime)
     elif S_ISREG(mode):
          sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
remote_file=input("enter the remote file: ")

local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, remote_file, local_path, preserve_mtime=False)