基于python的Dropbox,FTP上传下载工具

最近忍痛买了Pythonista这个APP,可以在iPhone上面跑python程序,简直不要太high,常用的库都内置了,如果没有你想要的库的话可以在电脑上用pip安装,之后传到手机上就好了,因此写了使用Dropbox和FTP上传,下载的工具,这样可以同步代码到手机上,ok,下面放出代码. 首先是dropbox的

#!/usr/bin/env python
# encoding: utf-8

"""
@version: ??
@author: liangliangyy
@license: Apache Licence 
@contact: liangliangyy@gmail.com
@site: https://www.lylinux.org/
@software: PyCharm
@file: DropBoxHelper.py
@time: 2016/6/23 19:39
"""

import requests
import dropbox
from  dropbox import files
from dropbox.files import FolderMetadata, FileMetadata, Metadata
import os
from os.path import basename


TOKEN = 'TOKEN'


class DropBoxHelper():
    def __init__(self, proxies):
        session = requests.session()
        if proxies:
            session.proxies = proxies
        self.__dropbox__ = dropbox.Dropbox(TOKEN, session=session)
        self.localbasepath = r'e:/dropbox'

    def DownLoadFile(self, filemetainfo):
        filename = filemetainfo.name
        localpath = self.localbasepath + filemetainfo.path_display.replace(filename, '')
        if not os.path.isdir(localpath):
            os.makedirs(localpath)
        print('start download ' + filemetainfo.path_display)
        self.__dropbox__.files_download_to_file(localpath + '/' + filename, filemetainfo.path_display)

    def DownLoadFileTree(self, path):
        items = self.__dropbox__.files_list_folder(path).entries
        for item in items:
            if type(item) is FileMetadata:
                self.DownLoadFile(item)
            else:
                print('enter dir :' + item.path_display)
                self.DownLoadFileTree(item.path_display)

    def UploadFile(self, path):
        if os.path.isfile(path):
            with open(path, 'rb') as f:
                dbxpath = path.replace(self.localbasepath, '')
                try:
                    print('start upload ' + dbxpath)
                except:
                    pass
                # print(dbxpath)
                # if dbxpath.startswith('/') or dbxpath.startswith('\\'):
                dbxpath = dbxpath.replace('\\', '/')
                self.__dropbox__.files_upload(f, dbxpath)

    def UploadFileTree(self, path=''):
        if not path:
            self.localbasepath = path
        for root, dirs, files in os.walk(self.localbasepath):
            for filepath in files:
                the_path = os.path.join(root, filepath)
                self.UploadFile(the_path)


if __name__ == '__main__':
    proxies = {
        'http': 'socks5://192.168.0.108:1080',
        'https': 'socks5://192.168.0.108:1080'
    }
    dropbox = DropBoxHelper(proxies)
    #dropbox.DownLoadFileTree('')
    dropbox.UploadFileTree(r'e:/dropbox')
    print('end')  

然后是FTP的

#!/usr/bin/env python
# encoding: utf-8


"""
@version: ??
@author: liangliangyy
@license: Apache Licence 
@contact: liangliangyy@gmail.com
@site: https://www.lylinux.org/
@software: PyCharm
@file: FtpHelper.py
@time: 2016/6/22 20:55
"""
from ftplib import FTP
import os

Host = '192.168.0.130'
User = 'server'
Password = '1'


class FtpHelper:
    def __init__(self, host):
        self.ftp = FTP(host=host)

    def login(self, username, password):
        self.ftp.login(user=username, passwd=password)

    def DownLoadFile(self, LocalFile, RemoteFile):
        print(RemoteFile)
        print(LocalFile)
        if (os.path.isfile(LocalFile)):
            print('delete')
            os.remove(LocalFile)
        file_handler = open(LocalFile, 'wb')
        self.ftp.retrbinary("RETR %s" % (RemoteFile), file_handler.write)
        file_handler.close()
        return True

    def DownLoadFileTree(self, localdir, remotedir):
        print('remotedir: ' + remotedir)
        print('localdir: ' + localdir)

        if not os.path.isdir(localdir):
            os.makedirs(localdir)
        self.ftp.cwd(remotedir)
        remotenames = self.ftp.nlst()
        print("RemoteNames", remotenames)

        for file in remotenames:
            Local = os.path.join(localdir, file)
            if self.isDir(file):
                self.DownLoadFileTree(Local, file)
            else:
                self.DownLoadFile(Local, file)
        self.ftp.cwd("..")
        return

    def UpLoadFile(self, LocalFile, RemoteFile):
        if LocalFile.endswith('pyc'):
            return False
        if os.path.isfile(LocalFile) == False:
            return False
        file_handler = open(LocalFile, "rb")
        self.ftp.storbinary('STOR %s' % RemoteFile, file_handler, 4096)
        file_handler.close()
        return True

    def UpLoadFileTree(self, LocalDir, RemoteDir):
        if LocalDir.startswith('.'):
            return
        if os.path.isdir(LocalDir) == False:
            return False
        print("LocalDir:", LocalDir)
        LocalNames = os.listdir(LocalDir)
        print("list:", LocalNames)
        print(RemoteDir)
        if not self.isDir(RemoteDir):
            self.ftp.mkd(RemoteDir)
        self.ftp.cwd(RemoteDir)
        for Local in LocalNames:
            src = os.path.join(LocalDir, Local)
            if os.path.isdir(src):
                self.UpLoadFileTree(src, Local)
            else:
                self.UpLoadFile(src, Local)

        self.ftp.cwd("..")
        return

    def isDir(self, path):
        try:
            self.ftp.cwd(path)
            self.ftp.cwd('..')
            return True
        except:
            return False


if __name__ == '__main__':
    ftphelper = FtpHelper(Host)
    ftphelper.login(username=User, password=Password)
    #ftphelper.DownLoadFileTree(r'/', 'pythonscript')
    ftphelper.UpLoadFileTree(r'F:\GIT\python','python')

发表评论

电子邮件地址不会被公开。 必填项已用*标注