我正在尝试使用Python的Paramiko模块从目录下载所有文件

时间:2014-05-06 15:11:54

标签: python upload download sftp paramiko

我已经完成了除此之外的所有其他工作,所以任何帮助都会非常感激,因为我一直试图让这部分工作几个小时,我搜索的任何内容似乎都没有帮助。

问题是我似乎无法使用下载功能(get())。我的上传功能(put())工作得很好。这段代码的作用是创建一个尚未在服务器上的所有文件的列表,然后使用glob.glob定位所有文件,它上传的那些那些还没有直接进入服务器。

我需要弄清楚的是,如何将目录中的所有文件下载到我的计算机上,以便我可以将它们上传到同一服务器上的不同目录。如果有更简单的方法,请让我们我知道。

import paramiko
import glob
import os
import fileinput
import shutil
from paramiko import sftp
from os import path

##This script uploads files from a local folder to a remote folder via
##SFTP and keeps track of which files have already been uploaded using "list.txt".

remotee = "//development//"
locall = "C:\\ftp\\Pangea"
complete = "C:\\moved"
mylist = "C:\\moved\\list.txt"
lastlist = []

class Server(object):
    def __init__(self, username, password, host, port=22):
        self.transport = paramiko.Transport((host, port))
        self.transport.connect(username=username, password=password)
        self.sftp = paramiko.SFTPClient.from_transport(self.transport)

    def upload(self, local, remote):
        self.sftp.put(local, remote)

    def download(self, remote, local):
        self.sftp.get(remote, local)

    def close(self):
        if self.transport.is_active():
            self.sftp.close()
            self.transport.close()

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.close()

with Server("username", "pass", "x.x.x.x") as server:
    for image in glob.glob("C:\\ftp\\Pangea\\*.*"):
        base = path.basename(image)
        server.upload(image, path.join(remotee, base))

for line in fileinput.input(locall + "\\list.txt"):
    lastlist.append(line.rstrip("\n"))

currentlist = os.listdir(locall)
newfiles = list(set(currentlist) - set(lastlist))

if len(newfiles) == 0:
    print("No files need to be uploaded")
    for src_dir, dirs, files in os.walk(locall):
        dst_dir = src_dir.replace(locall, complete)
    if not os.path.exists(dst_dir):
        os.mkdir(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.move(src_file, dst_dir)
        shutil.copy(mylist, locall)
else:
  for needupload in newfiles:
      print("Uploading " + locall + "\\" + needupload)
      with Server("username", "pass", "x.x.x.x") as server:
          for image in glob.glob("C:\\ftp\\Pangea\\*.*"):
              base = path.basename(image)
              server.upload(image, path.join(remotee, base))
      with open(locall + "\\list.txt", "a") as myfile:
          myfile.write(needupload + "\n")
      with open(complete + "\\list.txt", "a") as myfile:
          myfile.write(needupload + "\n")

0 个答案:

没有答案