使用python3实现ftp服务功能实例(客户端)
这篇文章主要为大家详细介绍了python3实现ftp服务功能,客户端的相应代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
客户端 main代码:
#Author by Andy #_*_ coding:utf-8 _*_ ''' This program is used to create a ftp client ''' import socket,os,json,time,hashlib,sys class Ftp_client(object): def init(self): self.client = socket.socket() def help(self): msg = '''useage: ls pwd cd dir(example: / .. . /var) put filename rm filename get filename mkdir directory name ''' print(msg) def connect(self,addr,port): self.client.connect((addr,port)) def auth(self): m = hashlib.md5() username = input("请输入用户名:").strip() m.update(input("请输入密码:").strip().encode()) password = m.hexdigest() user_info = { 'action':'auth', 'username':username, 'password':password} self.client.send(json.dumps(user_info).encode('utf-8')) server_response = self.client.recv(1024).decode() # print(server_response) return server_response def interactive(self): while True: msg = input(">>>:").strip() if not msg: print("不能发送空内容!") continue cmd = msg.split()[0] if hasattr(self,cmd): func = getattr(self,cmd) func(msg) else: self.help() continue def put(self,*args): cmd_split = args[0].split() if len(cmd_split) > 1: filename = cmd_split[1] if os.path.isfile(filename): filesize = os.stat(filename).st_size file_info = { "action":"put", "filename":filename, "size":filesize, "overriding":'True' } self.client.send( json.dumps(file_info).encode('utf-8') ) #防止粘包,等待服务器确认。 request_code = { '200': 'Ready to recceive data!', '210': 'Not ready to received data!' } server_response = self.client.recv(1024).decode() if server_response == '200': f = open(filename,"rb") send_size = 0 start_time = time.time() for line in f: self.client.send(line) send_size += len(line) send_percentage = int((send_size / filesize) * 100) while True: progress = ('\r已上传%sMB(%s%%)' % (round(send_size / 102400, 2), send_percentage)).encode( 'utf-8') os.write(1, progress) sys.stdout.flush() time.sleep(0.0001) break else: end_time = time.time() time_use = int(end_time - start_time) print("\nFile %s has been sent successfully!" % filename) print('\n平均下载速度%s MB/s' % (round(round(send_size / 102400, 2) / time_use, 2))) f.close() else: print("Sever isn't ready to receive data!") time.sleep(10) start_time = time.time() f = open(filename, "rb") send_size = 0 for line in f: self.client.send(line) send_size += len(line) # print(send_size) while True: send_percentage = int((send_size / filesize) * 100) progress = ('\r已上传%sMB(%s%%)' % (round(send_size / 102400, 2), send_percentage)).encode( 'utf-8') os.write(1, progress) sys.stdout.flush() # time.sleep(0.0001) break else: end_time = time.time() time_use = int(end_time - start_time) print("File %s has been sent successfully!" % filename) print('\n平均下载速度%s MB/s' % (round(round(send_size / 102400, 2) / time_use, 2))) f.close() else: print("File %s is not exit!" %filename) else: self.help() def ls(self,*args): cmd_split = args[0].split() # print(cmd_split) if len(cmd_split) > 1: path = cmd_split[1] elif len(cmd_split) == 1: path = '.' request_info = { 'action': 'ls', 'path': path } self.client.send(json.dumps(request_info).encode('utf-8')) sever_response = self.client.recv(1024).decode() print(sever_response) def pwd(self,*args): cmd_split = args[0].split() if len(cmd_split) == 1: request_info = { 'action': 'pwd', } self.client.send(json.dumps(request_info).encode("utf-8")) server_response = self.client.recv(1024).decode() print(server_response) else: self.help() def get(self,*args): cmd_split = args[0].split() if len(cmd_split) > 1: filename = cmd_split[1] file_info = { "action": "get", "filename": filename, "overriding": 'True' } self.client.send(json.dumps(file_info).encode('utf-8')) server_response = self.client.recv(1024).decode() #服务器反馈文件是否存在 self.client.send('0'.encode('utf-8')) if server_response == '0': file_size = int(self.client.recv(1024).decode()) # print(file_size) self.client.send('0'.encode('utf-8')) #确认开始传输数据 if os.path.isfile(filename): filename = filename+'.new' f = open(filename,'wb') receive_size = 0 m = hashlib.md5() start_time = time.time() while receive_size < file_size: if file_size - receive_size > 1024: # 还需接收不止1次 size = 1024 else: size = file_size - receive_size data = self.client.recv(size) m.update(data) receive_size += len(data) data_percent=int((receive_size / file_size) * 100) f.write(data) progress = ('\r已下载%sMB(%s%%)' %(round(receive_size/102400,2),data_percent)).encode('utf-8') os.write(1,progress) sys.stdout.flush() time.sleep(0.0001) else: end_time = time.time() time_use = int(end_time - start_time) print('\n平均下载速度%s MB/s'%(round(round(receive_size/102400,2)/time_use,2))) Md5_server = self.client.recv(1024).decode() Md5_client = m.hexdigest() print('文件校验中,请稍候...') time.sleep(0.3) if Md5_server == Md5_client: print('文件正常。') else: print('文件与服务器MD5值不符,请确认!') else: print('File not found!') client.interactive() else: self.help() def rm(self,*args): cmd_split = args[0].split() if len(cmd_split) > 1: filename = cmd_split[1] request_info = { 'action':'rm', 'filename': filename, 'prompt':'Y' } self.client.send(json.dumps(request_info).encode("utf-8")) server_response = self.client.recv(10240).decode() request_code = { '0':'confirm to deleted', '1':'cancel to deleted' } if server_response == '0': confirm = input("请确认是否真的删除该文件:") if confirm == 'Y' or confirm == 'y': self.client.send('0'.encode("utf-8")) print(self.client.recv(1024).decode()) else: self.client.send('1'.encode("utf-8")) print(self.client.recv(1024).decode()) else: print('File not found!') client.interactive() else: self.help() def cd(self,*args): cmd_split = args[0].split() if len(cmd_split) > 1: path = cmd_split[1] elif len(cmd_split) == 1: path = '.' request_info = { 'action':'cd', 'path':path } self.client.send(json.dumps(request_info).encode("utf-8")) server_response = self.client.recv(10240).decode() print(server_response) def mkdir(self,*args): request_code = { '0': 'Directory has been made!', '1': 'Directory is aleady exist!' } cmd_split = args[0].split() if len(cmd_split) > 1: dir_name = cmd_split[1] request_info = { 'action':'mkdir', 'dir_name': dir_name } self.client.send(json.dumps(request_info).encode("utf-8")) server_response = self.client.recv(1024).decode() if server_response == '0': print('Directory has been made!') else: print('Directory is aleady exist!') else: self.help() # def touch(self,*args): def run(): client = Ftp_client() # client.connect('10.1.2.3',6969) Addr = input("请输入服务器IP:").strip() Port = int(input("请输入端口号:").strip()) client.connect(Addr,Port) while True: if client.auth() == '0': print("Welcome.....") client.interactive() break else: print("用户名或密码错误!") continue
目录结构:
以上是使用python3实现ftp服务功能实例(客户端)的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

每天学习Python两个小时是否足够?这取决于你的目标和学习方法。1)制定清晰的学习计划,2)选择合适的学习资源和方法,3)动手实践和复习巩固,可以在这段时间内逐步掌握Python的基本知识和高级功能。

Python在开发效率上优于C ,但C 在执行性能上更高。1.Python的简洁语法和丰富库提高开发效率。2.C 的编译型特性和硬件控制提升执行性能。选择时需根据项目需求权衡开发速度与执行效率。

Python和C 各有优势,选择应基于项目需求。1)Python适合快速开发和数据处理,因其简洁语法和动态类型。2)C 适用于高性能和系统编程,因其静态类型和手动内存管理。

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

Python在科学计算中的应用包括数据分析、机器学习、数值模拟和可视化。1.Numpy提供高效的多维数组和数学函数。2.SciPy扩展Numpy功能,提供优化和线性代数工具。3.Pandas用于数据处理和分析。4.Matplotlib用于生成各种图表和可视化结果。

Python在Web开发中的关键应用包括使用Django和Flask框架、API开发、数据分析与可视化、机器学习与AI、以及性能优化。1.Django和Flask框架:Django适合快速开发复杂应用,Flask适用于小型或高度自定义项目。2.API开发:使用Flask或DjangoRESTFramework构建RESTfulAPI。3.数据分析与可视化:利用Python处理数据并通过Web界面展示。4.机器学习与AI:Python用于构建智能Web应用。5.性能优化:通过异步编程、缓存和代码优
