搜尋
首頁後端開發Python教學python3寫的簡單本機檔案上傳伺服器實例

python3寫的簡單本機檔案上傳伺服器實例

Jun 04, 2018 am 11:55 AM
python3文件本地

這篇文章主要介紹了關於python3寫的簡單本地文件上傳伺服器實例,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

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

大概功能是這樣:

1、取得本機檔案清單(包括資料夾)

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

3、之後增加了忽略列表,忽略文件類型

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

#大概就是這個樣子,哦了,丟程式碼丟程式碼

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os 
import os.path 
import paramiko
import datetime
import 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 1
	else:
		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 1
	else:
		# 存在则比较文件大小
		# 本地文件大小
		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 0
		else:
			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 = 0
for item in folder_list:
	target_folder_path = config['ssh_path'] + item
	create_folder_num = create_folder_num + check_folder(target_folder_path)

# 检查文件
update_file_num = 0
for item in file_list:
	if config['ignore_file_type_list'].count(os.path.splitext(item)[1]) == 0:
		local_file_path = config['local_path'] + item
		target_file_path = config['ssh_path'] + item
		if config['mandatory_update']:
			sftp.put(local_file_path,target_file_path)
			print('%s 强制更新成功' % (target_file_path))
			update_file_num = update_file_num + 1
		else:
			update_file_num = update_file_num + check_file(local_file_path, target_file_path)
	else:
		print('%s 在被忽略文件类型中,所以被忽略' % item)

# 检查ssh是否有需要删除的文件
delete_file_num = 0
for 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 + 1

end = 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更新記錄或別的方案。

相關推薦:

Python3之簡單搭建自帶伺服器

##

以上是python3寫的簡單本機檔案上傳伺服器實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何切成python陣列?您如何切成python陣列?May 01, 2025 am 12:18 AM

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

在什麼情況下,列表的表現比數組表現更好?在什麼情況下,列表的表現比數組表現更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何將Python數組轉換為Python列表?如何將Python數組轉換為Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

當Python中存在列表時,使用數組的目的是什麼?當Python中存在列表時,使用數組的目的是什麼?May 01, 2025 am 12:04 AM

choosearraysoverlistsinpythonforbetterperformanceandmemoryfliceSpecificScenarios.1)largenumericaldatasets:arraysreducememoryusage.2)績效 - 臨界雜貨:arraysoffersoffersOffersOffersOffersPoostSfoostSforsssfortasssfortaskslikeappensearch orearch.3)testessenforcety:arraysenforce:arraysenforc

說明如何通過列表和數組的元素迭代。說明如何通過列表和數組的元素迭代。May 01, 2025 am 12:01 AM

在Python中,可以使用for循環、enumerate和列表推導式遍歷列表;在Java中,可以使用傳統for循環和增強for循環遍歷數組。 1.Python列表遍歷方法包括:for循環、enumerate和列表推導式。 2.Java數組遍歷方法包括:傳統for循環和增強for循環。

什麼是Python Switch語句?什麼是Python Switch語句?Apr 30, 2025 pm 02:08 PM

本文討論了版本3.10中介紹的Python的新“匹配”語句,該語句與其他語言相同。它增強了代碼的可讀性,並為傳統的if-elif-el提供了性能優勢

Python中有什麼例外組?Python中有什麼例外組?Apr 30, 2025 pm 02:07 PM

Python 3.11中的異常組允許同時處理多個異常,從而改善了並發方案和復雜操作中的錯誤管理。

Python中的功能註釋是什麼?Python中的功能註釋是什麼?Apr 30, 2025 pm 02:06 PM

Python中的功能註釋將元數據添加到函數中,以進行類型檢查,文檔和IDE支持。它們增強了代碼的可讀性,維護,並且在API開發,數據科學和圖書館創建中至關重要。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境