上传下载程序,支持动态更换IP和端口, 上传下载, 进度条显示, 正则校验文件格式, hash校验文件完整性

本文主要是介绍上传下载程序,支持动态更换IP和端口, 上传下载, 进度条显示, 正则校验文件格式, hash校验文件完整性,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

支持动态更换IP和端口, 上传下载, 进度条显示, 正则校验文件格式, hash校验文件完整性

另有已封装好的exe文件

客户端

# coding=utf-8
from socket import *
import json
import struct
import os,re
import hashlibip = 0
port = 0# 打印进度条
def progress(percent, symbol='█', width=40):if percent > 1:  # 超过 100% 的时候让其停在 1percent = 1  # 可以避免进度条溢出show_progress = ("▌%%-%ds▌" % width) % (int(percent * width) * symbol)print("\r%s %.2f%%" % (show_progress, percent * 100), end='')# hash 校验
def Hash_md5(file_path:str):m = hashlib.md5()m.update(str(os.path.getsize(file_path)).encode("utf-8"))return m.hexdigest()# 连接
def connection():client = socket(AF_INET,SOCK_STREAM)client.connect((ip,port))return client# 下载
def download(client):client.send("1".encode("utf-8"))while 1:try:file_path = input("Please enter the file path(q/exit)>>").strip()if file_path.lower() == "q":breakif len(file_path) == 0:continueto_path = input("Please enter the save directory(q/back)>>").strip()if to_path.lower() == "q":continueif not os.path.isdir(to_path):print("not find");continueelse:file_name = input("Please enter filename(q/back)>>").strip()if file_name.lower() == "q":continueif re.search(r'[/|:*"<>\\]',file_name):print(r'Filenames cannot have these symbols:/|:*"<>\\');continuegoal_path = os.path.join(to_path,file_name)client.send(file_path.encode("utf-8"))bytes_4 = client.recv(4)if bytes_4.decode("utf-8") == "4044":print("not find");continueelse:header_bytes_len = struct.unpack("i",bytes_4)[0]header_bytes = client.recv(header_bytes_len)header_dic = json.loads(header_bytes.decode("utf-8"))date_len = header_dic["file_size"]hash_md5 = header_dic["hash"]recv_len = 0with open(goal_path,"wb")as f:while 1:date = client.recv(1024)recv_len += len(date)percent = recv_len / date_len  # 接收的比例progress(percent, width=40)    # 进度条的宽度40f.write(date)if recv_len == date_len: breakif hash_md5 == Hash_md5(goal_path):          # hash 值校验print("\nHash auth succeed\nFile saved...")continueelse:os.remove(goal_path)               # 校验失败内容删除print("Hash auth failed!!")except Exception as E:print(E);break# 上传
def uploading(client):client.send("2".encode("utf-8"))while 1:try:file_path = input("Please enter the path of the uploaded file(q/exit)>>").strip()if file_path.lower() == "q":breakfile_path = os.path.normpath(file_path)if not os.path.isfile(file_path):print("not find");continuegoal_path = input("Please enter the destination path(q/back)>>").strip()if goal_path.lower() == "q":continuegoal_path = os.path.normpath(goal_path)client.send(goal_path.encode("utf-8"))bytes_4 = client.recv(4)if bytes_4.decode("utf-8") == "4044":print("not find");continueelse:file_name = input("Please name the new file(q/back)>>").strip()if file_name.lower() == "q":continueif re.search(r'[/|:*"<>\\]',file_name):print(r'Filenames cannot have these symbols:/|:*"<>\\');continuegoal_file_path = os.path.join(goal_path,file_name)file_size = os.path.getsize(file_path)file_name = os.path.basename(file_path)md5 = Hash_md5(file_path)header_dic = {"file_name": file_name, "file_size": file_size, "hash": md5,"file_path":goal_file_path}header_json = json.dumps(header_dic)header_bytes = header_json.encode("utf-8")header_bytes_len = struct.pack("i", len(header_bytes))client.send(header_bytes_len)client.send(header_bytes)send_len = 0with open(file_path, "rb")as f:for line in f:send_len += len(line)percent = send_len / file_size # 接收的比例progress(percent, width=40)    # 进度条的宽度40client.send(line)print("\nsuccessfully upload!")except Exception as E:print(E);breakfunc_dic = {"1":["download ",download],"2":["upload",uploading],"3":["IP Settings",download],
}# 连接服务端ip和端口并选择功能
def run():while True:print("Please enter the correct IP and port")global ip,portip = input("Please enter IP(q/exit)>>").strip()if ip.lower() == "q":breakport = input("Please enter PORT(q/exit)>>").strip()if port.lower() == "q":breakif port.isdigit():port = int(port)else:print("Please enter the number")continuetry:client = connection()  # 检测连接是否建立成功except Exception as E:print(E);continuewhile 1:for k,v in func_dic.items():print(f"{k} : {v[0]}")select = input("Please select function>>")if select == "3":breakif select in func_dic:func_dic[select][1](client)run()

服务端

# coding=utf-8
from socket import *
import json
import struct
import os,hashlib# 绑定服务端地址
def connection():server = socket(AF_INET,SOCK_STREAM)server.bind((ip,port))server.listen(5)return server# 建立连接选择功能
def recv_send(server):while 1:print("connection...")conn,addr = server.accept()print(f"from {addr} conn")select = conn.recv(1)if select.decode("utf-8") == "1":download(conn)elif select.decode("utf-8") == "2":uploading(conn)# 客户端下载
def download(conn):while 1:try:file_path = conn.recv(1024)file_path = os.path.normpath(file_path.decode("utf-8"))if not os.path.isfile(file_path):conn.send("4044".encode("utf-8"))else:file_size = os.path.getsize(file_path)file_name = os.path.basename(file_path)m = hashlib.md5()m.update(str(file_size).encode("utf-8"))md5 = m.hexdigest()header_dic = {"file_name":file_name,"file_size":file_size,"hash":md5}header_json = json.dumps(header_dic)header_bytes = header_json.encode("utf-8")header_bytes_len = struct.pack("i",len(header_bytes))conn.send(header_bytes_len)conn.send(header_bytes)with open(file_path,"rb")as f:for line in f:conn.send(line)except Exception:break# 客户端的上传
def uploading(conn):while 1:try:dir_path = conn.recv(1024)dir_path = os.path.normpath(dir_path.decode("utf-8"))if not os.path.isdir(dir_path):conn.send("4044".encode("utf-8"));continueelse:conn.send("4444".encode("utf-8"))bytes_4 = conn.recv(4)header_bytes_len = struct.unpack("i", bytes_4)[0]header_bytes = conn.recv(header_bytes_len)header_dic = json.loads(header_bytes.decode("utf-8"))date_len = header_dic["file_size"]goal_file_path = header_dic["file_path"]recv_len = 0with open(goal_file_path, "wb")as f:while 1:date = conn.recv(1024)recv_len += len(date)f.write(date)if recv_len == date_len: breakcontinueexcept Exception as E:print(E);breakdef run():while True:print("Please enter the correct IP and port")global ip, portip = input("Please enter IP(q/exit)>>").strip()if ip.lower() == "q": breakport = input("Please enter PORT(q/exit)>>").strip()if port.lower() == "q": breakif port.isdigit():port = int(port)try:server = connection()except Exception as E:print(E);continuerecv_send(server)else:print("Please enter the number")continuerun()

这篇关于上传下载程序,支持动态更换IP和端口, 上传下载, 进度条显示, 正则校验文件格式, hash校验文件完整性的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/628077

相关文章

vue基于ElementUI动态设置表格高度的3种方法

《vue基于ElementUI动态设置表格高度的3种方法》ElementUI+vue动态设置表格高度的几种方法,抛砖引玉,还有其它方法动态设置表格高度,大家可以开动脑筋... 方法一、css + js的形式这个方法需要在表格外层设置一个div,原理是将表格的高度设置成外层div的高度,所以外层的div需要

SpringBoot实现动态插拔的AOP的完整案例

《SpringBoot实现动态插拔的AOP的完整案例》在现代软件开发中,面向切面编程(AOP)是一种非常重要的技术,能够有效实现日志记录、安全控制、性能监控等横切关注点的分离,在传统的AOP实现中,切... 目录引言一、AOP 概述1.1 什么是 AOP1.2 AOP 的典型应用场景1.3 为什么需要动态插

如何设置vim永久显示行号

《如何设置vim永久显示行号》在Linux环境下,vim默认不显示行号,这在程序编译出错时定位错误语句非常不便,通过修改vim配置文件vimrc,可以在每次打开vim时永久显示行号... 目录设置vim永久显示行号1.临时显示行号2.永www.chinasem.cn久显示行号总结设置vim永久显示行号在li

IDEA如何将String类型转json格式

《IDEA如何将String类型转json格式》在Java中,字符串字面量中的转义字符会被自动转换,但通过网络获取的字符串可能不会自动转换,为了解决IDEA无法识别JSON字符串的问题,可以在本地对字... 目录问题描述问题原因解决方案总结问题描述最近做项目需要使用Ai生成json,可生成String类型

VUE动态绑定class类的三种常用方式及适用场景详解

《VUE动态绑定class类的三种常用方式及适用场景详解》文章介绍了在实际开发中动态绑定class的三种常见情况及其解决方案,包括根据不同的返回值渲染不同的class样式、给模块添加基础样式以及根据设... 目录前言1.动态选择class样式(对象添加:情景一)2.动态添加一个class样式(字符串添加:情

Python中实现进度条的多种方法总结

《Python中实现进度条的多种方法总结》在Python编程中,进度条是一个非常有用的功能,它能让用户直观地了解任务的进度,提升用户体验,本文将介绍几种在Python中实现进度条的常用方法,并通过代码... 目录一、简单的打印方式二、使用tqdm库三、使用alive-progress库四、使用progres

macOS怎么轻松更换App图标? Mac电脑图标更换指南

《macOS怎么轻松更换App图标?Mac电脑图标更换指南》想要给你的Mac电脑按照自己的喜好来更换App图标?其实非常简单,只需要两步就能搞定,下面我来详细讲解一下... 虽然 MACOS 的个性化定制选项已经「缩水」,不如早期版本那么丰富,www.chinasem.cn但我们仍然可以按照自己的喜好来更换

shell脚本快速检查192.168.1网段ip是否在用的方法

《shell脚本快速检查192.168.1网段ip是否在用的方法》该Shell脚本通过并发ping命令检查192.168.1网段中哪些IP地址正在使用,脚本定义了网络段、超时时间和并行扫描数量,并使用... 目录脚本:检查 192.168.1 网段 IP 是否在用脚本说明使用方法示例输出优化建议总结检查 1

SpringCloud配置动态更新原理解析

《SpringCloud配置动态更新原理解析》在微服务架构的浩瀚星海中,服务配置的动态更新如同魔法一般,能够让应用在不重启的情况下,实时响应配置的变更,SpringCloud作为微服务架构中的佼佼者,... 目录一、SpringBoot、Cloud配置的读取二、SpringCloud配置动态刷新三、更新@R

Redis连接失败:客户端IP不在白名单中的问题分析与解决方案

《Redis连接失败:客户端IP不在白名单中的问题分析与解决方案》在现代分布式系统中,Redis作为一种高性能的内存数据库,被广泛应用于缓存、消息队列、会话存储等场景,然而,在实际使用过程中,我们可能... 目录一、问题背景二、错误分析1. 错误信息解读2. 根本原因三、解决方案1. 将客户端IP添加到Re