作业8:ftp
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了作业8:ftp相关的知识,希望对你有一定的参考价值。
客户端:
1 import socket,os,sys,json,re 2 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 3 sys.path.append(BASE_DIR) 4 from config import settings 5 from lib import commons 6 #客户端 7 8 def login(conn): 9 while True: 10 username=input(‘请输入用户名:‘) 11 pwd=input(‘请输入密码:‘) 12 login_info={‘username‘:username,‘pwd‘:pwd} 13 #json_data=(json.dump(login_info)).encode(‘utf-8‘) 14 conn.sendall(bytes(json.dumps(login_info), ‘utf-8‘)) 15 if (conn.recv(1024)).decode()==‘4002‘: 16 print(‘授权成功‘) 17 break 18 else: 19 print(‘用户名或密码错误...‘) 20 21 def cmd(conn,inp): 22 conn.sendall(inp.encode(‘utf-8‘)) 23 basic_info_str=str(conn.recv(1024).decode()) 24 if basic_info_str==‘4001‘: 25 login(conn) 26 else : 27 conn.sendall(b"XiaJiBaFaJiuXingLe") 28 print(basic_info_str) 29 result_length=int(basic_info_str.split(‘|‘,1)[1]) 30 has_received=0 31 content_bytes=b‘‘ 32 while has_received<result_length: 33 fetch_bytes=conn.recv(1024) 34 content_bytes+=fetch_bytes 35 has_received+=len(fetch_bytes) 36 cmd_result=content_bytes.decode() 37 print(cmd_result) 38 39 def post(conn,inp): #post|10.txt 11.txtyg200.jpg 40 method,file_paths=inp.split(‘|‘,1) 41 local_path,target_path=re.split(‘\s*‘,file_paths,1) 42 file_byte_size=os.stat(local_path).st_size 43 file_name=os.path.basename(local_path) 44 file_md5=commons.fetch_file_md5(local_path) #本地文件的各种乱七八糟的值 45 post_info=‘post|%s|%s|%s|%s‘%(file_byte_size, file_name, file_md5, target_path) 46 conn.sendall(post_info.encode("utf-8")) 47 result_exist=(conn.recv(1024)).decode() 48 if result_exist==‘4001‘: 49 login(conn) 50 return 51 has_sent=0 52 if result_exist == "2003": 53 inp_continue = input(‘文件已经存在,是否续传?Y/N‘) 54 if inp_continue.upper() == "Y": 55 conn.sendall(b‘2004‘) 56 result_continue_pos = str(conn.recv(1024), ‘utf-8‘) 57 has_sent = int(result_continue_pos) 58 else: 59 conn.sendall(b‘2005‘) 60 61 file_obj = open(local_path, ‘rb‘) 62 file_obj.seek(has_sent) 63 while file_byte_size > has_sent: 64 data = file_obj.read(1024) 65 conn.sendall(data) 66 has_sent += len(data) 67 commons.bar(has_sent, file_byte_size) # 显示进度 68 file_obj.close() 69 print(‘上传成功‘) 70 71 def get(conn,inp): #get|1.txt 2.txt 72 # func,file_paths=inp.split(‘|‘,1) 73 # target_path,local_path=re.split(‘\s*‘,file_paths,1) 74 conn.sendall(inp.encode(‘utf-8‘)) 75 76 77 result_exist = (conn.recv(1024)).decode() 78 79 if result_exist == ‘4001‘: 80 login(conn) 81 return 82 else:pass 83 print(‘2‘) 84 a=(conn.recv(1024)).decode() 85 file_byte_size, file_name, file_md5,local_path=(a).split(‘|‘) 86 file_abs_md5_path=os.path.join(settings.FILE_GPS,local_path) 87 print(‘3‘) 88 has_received = 0 89 if os.path.exists(file_abs_md5_path): 90 user_inp=input("是否续传 Y/N:") 91 if user_inp==‘Y‘: 92 f=open(file_abs_md5_path,‘ab‘) 93 has_file_size = os.stat(file_abs_md5_path).st_size 94 has_received+= has_file_size #这个是大佬 95 96 97 else: 98 f=open(file_abs_md5_path,‘wb‘) 99 else : 100 f=open(file_abs_md5_path,‘wb‘) 101 102 103 conn.sendall( str(has_received).encode(‘utf-8‘) ) 104 file_byte_size=int(file_byte_size) 105 while has_received < file_byte_size: 106 107 data=conn.recv(1024) 108 f.write(data) 109 has_received+=len(data) 110 111 f.close() 112 113 114 def help_info(): 115 print(""" 116 cmd|命令 117 post|上传文件路径 118 get|下载文件路径 119 exit|退出 120 """) 121 122 def execute(conn): 123 choice_dic={ 124 ‘cmd‘:cmd, 125 ‘get‘:get, 126 ‘post‘:post, 127 } 128 help_info() 129 while True: 130 inp=input("请输入:") 131 if inp==‘help‘: 132 help_info() 133 continue 134 choice=inp.split(‘|‘)[0] 135 if choice==‘exit‘: 136 return 137 if choice in choice_dic: 138 func=choice_dic[choice] 139 func(conn,inp) 140 141 142 143 def main(): 144 ip_port=(settings.server,settings.port) 145 conn=socket.socket() 146 conn.connect(ip_port) 147 welcome_bytes=conn.recv(1024) 148 print(welcome_bytes.decode()) 149 150 execute(conn) 151 152 conn.close() 153 main()
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import sys 4 import hashlib 5 6 7 def fetch_file_md5(file_path): 8 obj = hashlib.md5() 9 f = open(file_path, ‘rb‘) 10 while True: 11 b = f.read(8096) 12 if not b: 13 break 14 obj.update(b) 15 f.close() 16 return obj.hexdigest() 17 18 19 def bar(num=1, total=100): 20 rate = float(num) / float(total) 21 rate_num = int(rate * 100) 22 temp = ‘\r%d %%‘ % (rate_num, ) 23 sys.stdout.write(temp) 24 sys.stdout.flush()
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import os,sys 4 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 5 6 server = ‘127.0.0.1‘ 7 port = 9992 8 9 10 FILE_GPS = os.path.join(BASE_DIR, ‘download‘)
服务器端:
1 import socket,os,sys,socketserver,json,re,subprocess 2 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 3 sys.path.append(BASE_DIR) 4 from config import settings 5 from lib import commons 6 #网络端 7 8 class MultiServerHandler(socketserver.BaseRequestHandler): 9 def handle(self): 10 conn=self.request 11 conn.sendall("欢迎登陆".encode(‘utf-8‘)) 12 obj=Action(conn) 13 while True: 14 client_bytes=conn.recv(1024) 15 if not client_bytes: #没有数据了,跳出循环 16 break 17 client_str=str(client_bytes.decode()) 18 if obj.has_login: 19 o=client_str.split(‘|‘,1) 20 if len(o)>0: 21 func=getattr(obj,o[0]) #反射,组成一个‘函数’ Action.cmd 22 func(client_str) 23 else: 24 conn.sendall("格式输入错误".encode(‘utf-8‘)) 25 else: 26 obj.login(client_str) 27 conn.close() 28 29 30 31 class MultiServer(object): 32 def __init__(self): 33 server=socketserver.ThreadingTCPServer((settings.BIND_HOST,settings.BIND_PORT),MultiServerHandler) 34 server.serve_forever() 35 36 class Action(object): 37 def __init__(self,conn): 38 self.conn=conn 39 self.has_login=False 40 self.username=None 41 self.home=None 42 self.current_dir=None 43 44 def login(self,origin): 45 self.conn.sendall(b‘4001‘) 46 while True: 47 login_str=self.conn.recv(1024).decode() 48 login_dict=json.loads(login_str) 49 if login_dict[‘username‘]==‘1‘ and login_dict[‘pwd‘]==‘1‘: 50 self.conn.sendall(b‘4002‘) 51 self.has_login = True # 更改变量 52 self.username = ‘wupeiqi‘ 53 self.home = os.path.join(settings.USER_HOME, self.username) # 组合成家路径 54 #self.current_dir = os.path.join(settings.USER_HOME, self.username) # 什么鬼,搞不懂 55 break 56 else: 57 self.conn.sendall(b‘4003‘) 58 59 def cmd(self,origin): 60 func,command=origin.split(‘|‘,1) 61 print(func,command) 62 try: 63 result_bytes = subprocess.check_output(command, shell=True) 64 # result_bytes # gbk字节 65 result_bytes = bytes(str(result_bytes, encoding=‘gbk‘), encoding=‘utf-8‘) 66 except Exception as e: 67 result_bytes = bytes(‘error cmd‘, encoding=‘utf-8‘) 68 info_str = "info|%d" % len(result_bytes) 69 self.conn.sendall(bytes(info_str, ‘utf-8‘)) 70 ack = self.conn.recv(1024) 71 self.conn.sendall(result_bytes) 72 73 def post(self,origin): 74 func,file_byte_size,file_name,file_md5,target_path=origin.split(‘|‘,4) 75 file_abs_md5_path=os.path.join(self.home,target_path) 76 has_received=0 77 file_byte_size=int(file_byte_size) 78 if os.path.exists(file_abs_md5_path): #如果文件存在 79 self.conn.sendall(b"2003") 80 is_continue=(self.conn.recv(1024)).decode() 81 if is_continue == ‘2004‘: #如果继续传 82 has_file_size=os.stat(file_abs_md5_path).st_size 83 self.conn.sendall( str(has_file_size).encode(‘utf-8‘) ) 84 has_received+=has_file_size 85 f=open(file_abs_md5_path,‘ab‘) 86 else: 87 f=open(file_abs_md5_path,‘wb‘) 88 else: 89 self.conn.sendall(b‘2002‘) 90 f=open(file_abs_md5_path,‘wb‘) 91 92 while file_byte_size > has_received: 93 data=self.conn.recv(1024) 94 f.write(data) 95 has_received+=len(data) 96 f.close() 97 98 def get(self,origin): #get|11.txt local.txt 99 func,file_paths=origin.split(‘|‘,1) 100 target_path_name,local_path=re.split(‘\s*‘,file_paths,1) 101 102 target_path=os.path.join(self.home,target_path_name) #文件路径 103 104 file_byte_size = os.stat(target_path).st_size 105 file_name = os.path.basename(target_path) 106 file_md5 = commons.fetch_file_md5(target_path) 107 #print(file_byte_size,file_name,file_md5,local_path) 108 self.conn.sendall(b‘123‘) 109 self.conn.sendall((‘%s|%s|%s|%s‘ % (file_byte_size, file_name, file_md5, local_path)).encode(‘utf-8‘)) 110 #self.conn.sendall((‘%s|%s|%s|%s‘ % (file_byte_size, file_name, file_md5, local_path)).encode(‘utf-8‘)) 111 #print(‘1‘) 112 file_seek = (self.conn.recv(1024)).decode() 113 #print(‘3‘) 114 file_seek = int(file_seek) 115 #print(‘4‘) 116 file_obj=open(target_path,‘rb‘) 117 #print(‘5‘) 118 file_obj.seek(file_seek) 119 #print(‘2‘) 120 while file_byte_size > file_seek: 121 data=file_obj.read(1024) 122 self.conn.sendall(data) 123 file_seek+=len(data) 124 125 #self.conn.recv(commons.bar(file_seek, file_byte_size)) 126 commons.bar(file_seek, file_byte_size) 127 128 file_obj.close() 129 130 131 132 133 MultiServer()
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import sys 4 import hashlib 5 6 7 def fetch_file_md5(file_path): 8 obj = hashlib.md5() 9 f = open(file_path, ‘rb‘) 10 while True: 11 b = f.read(8096) 12 if not b: 13 break 14 obj.update(b) 15 f.close() 16 return obj.hexdigest() 17 18 19 def bar(num=1, total=100): 20 rate = float(num) / float(total) 21 rate_num = int(rate * 100) 22 temp = ‘\r%d %%‘ % (rate_num, ) 23 sys.stdout.write(temp) 24 sys.stdout.flush()
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import os 5 6 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 7 8 9 BIND_HOST = ‘127.0.0.1‘ 10 BIND_PORT = 9992 11 12 USER_HOME = os.path.join(BASE_DIR, ‘home‘) 13 14 USER_ACCOUNT = { 15 ‘alex‘: { 16 ‘password‘: ‘alex123‘, 17 ‘quotation‘: 1000000, 18 ‘expire‘: ‘2016-01-22‘ 19 }, 20 ‘rain‘: { 21 ‘password‘: ‘rain123‘, 22 ‘quotation‘: 2000000, 23 ‘expire‘: ‘2016-01-22‘ 24 }, 25 }
以上是关于作业8:ftp的主要内容,如果未能解决你的问题,请参考以下文章