python3寫的簡單本地檔案上傳伺服器執行個體

來源:互聯網
上載者:User
這篇文章主要介紹了關於python3寫的簡單本地檔案上傳伺服器執行個體,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

python是個很好玩的東西?好吧我隨口說的,反正因為各種原因(其實到底是啥我也不知道),簡單的學習了下python,然後寫了一個上傳檔案上伺服器的小玩具練手。

大概功能是這樣:

1、擷取本地檔案清單(包括檔案夾)

2、檢查伺服器上是否存在,不存在直接上傳,存在的話,檔案夾無視,檔案比較大小,大小不一致則覆蓋,最後檢查伺服器上是否存在本地沒有的檔案,存在則刪除

3、之後增加了忽略列表,忽略檔案類型

4、然後增加了重啟tomcat,但是這個功能未進行測試

大概就是這個樣子,哦了,丟代碼丟代碼

#!/usr/bin/env python3# -*- coding: utf-8 -*-import os import os.path import paramikoimport datetimeimport re# 配置屬性config = {#本地項目路徑'local_path' : '',# 伺服器項目路徑'ssh_path' : '',# 項目名'project_name' : '',# 忽視列表'ignore_list' : [],# ssh地址、連接埠、使用者名稱、密碼'hostname' : '','port' : 22,'username' : '','password' : '',# 是否強制更新'mandatory_update' : False,# 更新完成後是否重啟tomcat'restart_tomcat' : False,# tomcat bin地址'tomcat_path' : '',# 被忽略的檔案類型'ignore_file_type_list' : []}# 檢查檔案夾是否存在,不存在則建立def check_folder(path):stdin, stdout, stderr = ssh.exec_command('find ' + path)result = stdout.read().decode('utf-8')if len(result) == 0 :print('目錄 %s 不存在,建立目錄' % path)ssh.exec_command('mkdir ' + path)print('%s 建立成功' % path)return 1else:print('目錄 %s 已存在' % path)return 0# 檢查檔案是否存在,不存在直接上傳,存在檢查大小是否一樣,不一樣則上傳def check_file(local_path, ssh_path):# 檢查檔案是否存在,不存在直接上傳stdin, stdout, stderr = ssh.exec_command('find ' + ssh_path)result = stdout.read().decode('utf-8')if len(result) == 0 :sftp.put(local_path,ssh_path)print('%s 上傳成功' % (ssh_path))return 1else:# 存在則比較檔案大小# 本地檔案大小lf_size = os.path.getsize(local_path)# 目標檔案大小stdin, stdout, stderr = ssh.exec_command('du -b ' + ssh_path)result = stdout.read().decode('utf-8')tf_size = int(result.split('\t')[0])print('本地檔案大小為:%s,遠程檔案大小為:%s' % (lf_size, tf_size))if lf_size == tf_size:print('%s 大小與本地檔案相同,不更新' % (ssh_path))return 0else:sftp.put(local_path,ssh_path)print('%s 更新成功' % (ssh_path))return 1# 上傳流程開始print('上傳開始')begin = datetime.datetime.now()# 資料夾清單folder_list = []# 檔案清單file_list = []# ssh上檔案清單ssh_file_list = []for parent,dirnames,filenames in os.walk(config['local_path']+config['project_name']):  #初始設定檔案夾列表 for dirname in dirnames: p = os.path.join(parent,dirname) folder_list.append(p[p.find(config['project_name']):]) #初始設定檔案列表 for filename in filenames: if config['ignore_list'].count(filename) == 0: p = os.path.join(parent,filename) file_list.append(p[p.find(config['project_name']):])print('共有檔案夾%s個,檔案%s個' % (len(folder_list),len(file_list)))# ssh控制台ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(hostname=config['hostname'], port=config['port'], username=config['username'], password=config['password'])# ssh傳輸transport = paramiko.Transport((config['hostname'],config['port']))transport.connect(username=config['username'],password=config['password'])sftp = paramiko.SFTPClient.from_transport(transport)# 檢查根目錄是否存在root_path = config['ssh_path'] + config['project_name']stdin, stdout, stderr = ssh.exec_command('find ' + root_path)result = stdout.read().decode('utf-8')if len(result) == 0 :print('目錄 %s 不存在,建立目錄' % root_path)ssh.exec_command('mkdir ' + root_path)print('%s 建立成功' % root_path)else:print('目錄 %s 已存在,擷取所有檔案' % root_path)ssh_file_list = re.split('\n',result)# 檢查檔案夾create_folder_num = 0for item in folder_list:target_folder_path = config['ssh_path'] + itemcreate_folder_num = create_folder_num + check_folder(target_folder_path)# 檢查檔案update_file_num = 0for item in file_list:if config['ignore_file_type_list'].count(os.path.splitext(item)[1]) == 0:local_file_path = config['local_path'] + itemtarget_file_path = config['ssh_path'] + itemif config['mandatory_update']:sftp.put(local_file_path,target_file_path)print('%s 強制更新成功' % (target_file_path))update_file_num = update_file_num + 1else:update_file_num = update_file_num + check_file(local_file_path, target_file_path)else:print('%s 在被忽略檔案類型中,所以被忽略' % item)# 檢查ssh是否有需要刪除的檔案delete_file_num = 0for item in ssh_file_list:temp = item[item.find(config['project_name']):]if folder_list.count(temp) == 0 and file_list.count(temp) == 0 and temp != config['project_name'] and temp != '':print('%s 在本地不存在,刪除' % item)ssh.exec_command('rm -rf ' + item)delete_file_num = delete_file_num + 1end = datetime.datetime.now()print('本次上傳結束:建立檔案夾%s個,更新檔案%s個,刪除檔案%s個,耗時:%s' % (create_folder_num, update_file_num, delete_file_num, end-begin))if config['restart_tomcat']:print('關閉tomcat')ssh.exec_command('sh ' + config['tomcat_path'] + 'shutdown.sh')print('啟動tomcat')ssh.exec_command('sh ' + config['tomcat_path'] + 'startup.sh')# 關閉串連sftp.close()ssh.close()

最後加了個強制更新,即不管三七二十一隻要不在忽略列表中直接上傳覆蓋,畢竟通過比較大小來更新檔案有機率出問題,比如我把1改成2那麼通過檔案大小是無法對比出來的,如果之後有時間的話會琢磨下拉取git更新記錄或者別的方案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.