佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Python使用sftp實現(xiàn)傳文件夾和文件

Python使用sftp實現(xiàn)傳文件夾和文件

熱門標(biāo)簽:電話運營中心 百度AI接口 客戶服務(wù) 呼叫中心市場需求 Win7旗艦版 企業(yè)做大做強(qiáng) 硅谷的囚徒呼叫中心 語音系統(tǒng)

利用python的sftp實現(xiàn)文件上傳,可以是文件,也可以是文件夾。

版本Python2.7.13 應(yīng)該不用pip安裝更多的插件,都是自帶的

不多說 上代碼

# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import paramiko
import os

_XFER_FILE = 'FILE'
_XFER_DIR  = 'DIR'

class MainWindow(object):
    # 構(gòu)造方法
    def __init__(self, arg):
        # 超類調(diào)用
        super(MainWindow, self).__init__()

        # 賦值參數(shù)[字典]
        # 參數(shù)格式 arg = {'ip':'填ip','user':'用戶名','password':'密碼','port':22}
        self.arg = arg
        # 賦值參數(shù)[FTP]
        self.sftp = None

        # 調(diào)試日志
        print self.arg


    # 啟動程序
    def startup(self):
        # 連接FTP
        if self.sftp != None:
            print u'您已經(jīng)成功連接了'
        tmpstr = u'開始連接...用戶名:'+self.arg['user']+u'  密碼:'+self.arg['password']+' IP:'+self.arg['ip']+u' 端口:'+str(self.arg['port'])
        print tmpstr
        try:
            transport = paramiko.Transport((self.arg['ip'], self.arg['port']))
            transport.connect(username=self.arg['user'], password=self.arg['password'])
            self.sftp = paramiko.SFTPClient.from_transport(transport)
            print (u'連接成功 '+self.arg['ip'])
        except Exception as e:
            print u'連接失?。?+str(e)

    # 關(guān)閉程序
    def shutdown(self):
        # 關(guān)閉FTP
        if self.sftp:
            self.sftp.close() 
            print '### disconnect sftp server: %s!'%self.arg['ip']
            self.sftp = None 

    # 處理上傳
    def upload(self, source, target, replace):
        ### 操作數(shù)據(jù)
        # 來源路徑
        source = source.replace('\\', '/')
        # 目標(biāo)路徑
        target = target.replace('\\', '/')


        ### 驗證數(shù)據(jù)
        if not os.path.exists(source):
            print u'來源資源不存在,請檢查:' + source
            return


        ### 格式數(shù)據(jù)
        # 格式化目標(biāo)路徑
        self.__makePath(target)


        ### 處理數(shù)據(jù)
        # 文件媒體數(shù)據(jù)(文件類型, 文件名稱)
        filetype, filename = self.__filetype(source)
        # 判斷文件類型
        if filetype == _XFER_DIR:
            # 1.目錄 
            self.uploadDir(source, target, replace)
        elif filetype == _XFER_FILE:
            # 2.文件 
            self.uploadFile(source, filename, replace)


    # 傳送目錄
    def uploadDir(self, source, target, replace):
        ### 驗證數(shù)據(jù)
        # 判斷目錄存在
        if not os.path.isdir(source):   
            print u'這個函數(shù)是用來傳送本地目錄的'
            return

        ### 處理數(shù)據(jù)
        # 遍歷目錄內(nèi)容,上傳資源
        for file in os.listdir(source):
            # 資源路徑
            filepath = os.path.join(source, file) 

            # 判斷資源文件類型
            if os.path.isfile(filepath): 
                # 1.文件
                self.uploadFile(filepath, file, replace) 
            elif os.path.isdir(filepath):
                # 2.目錄
                try:
                    self.sftp.chdir(file) 
                except:
                    self.sftp.mkdir(file)
                    self.sftp.chdir(file) 
                self.uploadDir(filepath, file, replace)

        ### 重置數(shù)據(jù)
        # 返回上一層目錄
        self.sftp.chdir('..') 

    # 傳送文件
    def uploadFile(self, filepath, filename, replace):
        ### 驗證數(shù)據(jù)
        # 驗證文件類型
        if not os.path.isfile(filepath):
            print u'這個函數(shù)是用來傳送單個文件的'
            return
        # 驗證文件存在
        if not os.path.exists(filepath):
            print u'err:本地文件不存在,檢查一下'+filepath
            return
        # 驗證FTP已連接
        if self.sftp == None:
            print u'sftp 還未鏈接'
            return


        ### 處理數(shù)據(jù)
        # 判斷文件存在是否覆蓋
        if not replace:
            if filename in self.sftp.listdir():
                print u'[*] 這個文件已經(jīng)存在了,選擇跳過:' + filepath + ' -> ' + self.sftp.getcwd() + '/' + filename
                return
        # 上傳文件
        try:
            self.sftp.put(filepath, filename)
            print u'[+] 上傳成功:' + filepath + ' -> ' + self.sftp.getcwd() + '/' + filename
        except Exception as e:
            print u'[+] 上傳失敗:' + filepath + ' because ' + str(e)


    # 獲得文件媒體數(shù)據(jù)({文件/目錄, 文件名稱})
    def __filetype(self, source):
        # 判斷文件類型
        if os.path.isfile(source):
            # 1.文件
            index = source.rfind('/')
            return _XFER_FILE, source[index+1:]
        elif os.path.isdir(source):  
            # 2.目錄
            return _XFER_DIR, ''


    # 創(chuàng)建目標(biāo)路徑
    # 說明: 目標(biāo)路徑不存在則依次創(chuàng)建路徑目錄
    def __makePath(self, target):
        # 切換根目錄
        self.sftp.chdir('/')

        # 分割目標(biāo)目錄為目錄單元集合
        data = target.split('/')
        # 進(jìn)入目標(biāo)目錄, 目錄不存在則創(chuàng)建
        for item in data:
            try:
                self.sftp.chdir(item) 
                print u'要上傳的目錄已經(jīng)存在,選擇性進(jìn)入合并:' + item
            except:
                self.sftp.mkdir(item)
                self.sftp.chdir(item) 
                print u'要上傳的目錄不存在,創(chuàng)建目錄:' + item




if __name__ == '__main__':
    # """
    # 先熟悉一下sftp有哪些用法  sftp.listdir(可以傳參可以為空) 返回當(dāng)前目錄下清單列表
    # mkdir 創(chuàng)建目錄對應(yīng)rmdir   sftp.put(本地路徑,遠(yuǎn)程要存的文件名) chdir進(jìn)入子目錄
    # """
    arg = {'ip':'填ip','user':'填用戶名','password':'填密碼','port':22}

    me  = MainWindow(arg)
    me.startup()
    # 要上傳的本地文件夾路徑
    source = r'E:\xampp\backup\mysql\cto'
    # 上傳到哪里 [遠(yuǎn)程目錄]
    target = r'/home/www/cto/wp-superdo/backup/db'
    replace = False

    me.upload(source, target, replace)
    me.shutdown()



def main(source, target, replace=False):
    arg = {'ip':填ip,'user':填用戶名,'password':填密碼,'port':22}

    me  = MainWindow(arg)
    me.startup()

    me.upload(source, target, replace)
    me.shutdown()

因為Python2.7對中文的支持不是很好所以如果出現(xiàn)中文錯誤
修改一下 Python27\Lib\site-packages\paramiko\py3compat.py

還有

最后上一下執(zhí)行結(jié)果

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

標(biāo)簽:山西 長沙 喀什 崇左 山西 海南 安康 濟(jì)南

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python使用sftp實現(xiàn)傳文件夾和文件》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    扎鲁特旗| 积石山| 枣阳市| 江孜县| 灵石县| 锡林浩特市| 奉贤区| 上栗县| 方山县| 靖西县| 宿迁市| 柳州市| 牙克石市| 兰考县| 北辰区| 吉木萨尔县| 彩票| 射阳县| 万安县| 沙河市| 平顶山市| 合阳县| 秀山| 定襄县| 深州市| 桐城市| 霍邱县| 苗栗市| 金平| 贵阳市| 万山特区| 防城港市| 遂川县| 来凤县| 互助| 湛江市| 洛浦县| 开平市| 绥江县| 布尔津县| 康定县|