从零开始学Python08作业源码:开发简单的FTP(仅供参考)
- 服务器端:server_server.py
1 #!usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # auther:Mr.chen 4 # 描述: 5 6 import socket 7 import os 8 import threading 9 import time 10 import json 11 from user_users import PersonInfo 12 13 DIR = os.path.dirname(os.path.abspath(__file__)) 14 DIR = DIR+'/Folder/' 15 16 TAG = True 17 18 19 20 def tcplink(conn,addr): 21 """ 22 tcp请求分析函数 23 :param conn: tcp连接对象 24 :param addr: 连接地址 25 :return: 26 """ 27 print ("收到来自{0}的连接请求".format(addr)) 28 conn.send('与主机通信中...') 29 while TAG: 30 try: 31 data = conn.recv(4096) 32 time.sleep(1) 33 if not data: 34 break 35 else: 36 print (data) 37 if data == 'ls': 38 P.view_file(conn) 39 continue 40 action,filename = data.strip().split() 41 action = action.lower() 42 if action == 'put': 43 re = P.Recvfile(conn,filename) 44 if re == True: 45 print ("文件接收成功!") 46 else: 47 print ("文件接收失败!") 48 elif action == 'get': 49 50 P.Sendfile(conn,filename) 51 elif action == 'login': 52 name, password = filename.split(',') 53 P = PersonInfo(name, password) 54 re = P.login() 55 if re == True: 56 conn.send('Ready!') 57 else: 58 conn.send('False!') 59 elif action == 'register': 60 name,password = filename.split(',') 61 P = PersonInfo(name, password) 62 re = P.register() 63 if re == True: 64 conn.send('Ready!') 65 else: 66 conn.send('False!') 67 else: 68 print ("请求方的输入有错!") 69 continue 70 except Exception,e: 71 print "tcplink处理出现问题",e 72 break 73 74 75 76 77 if __name__ == '__main__': 78 host = 'localhost' 79 port = 8888 80 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 81 s.bind((host,port)) 82 s.listen(5) 83 print ("服务运行中:正在监听{0}地址的{1}端口:".format(host,port)) 84 while TAG: 85 # 接受一个新连接 86 conn,addr = s.accept() 87 # 创建一个新线程处理TCP连接 88 t = threading.Thread(target=tcplink,args=(conn,addr)) 89 t.start()
- 服务器端:user_users.py
1 #!usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # auther:Mr.chen 4 # 描述: 5 6 import time 7 import os 8 import pickle 9 10 11 class PersonInfo: 12 """ 13 用户模型类 14 """ 15 DIR = os.path.dirname(os.path.abspath(__file__)) 16 DIR = DIR + '/Folder/' 17 ConfigDir = DIR.replace('Folder','db') 18 19 def __init__(self,name,password): 20 self.Name = name #用户名 21 self.Password = password #密码 22 self.DIR = PersonInfo.DIR + self.Name +'/' #用户家目录 23 24 25 def login(self): 26 """ 27 用户登陆 28 :return: 29 """ 30 dict = PersonInfo.config_read() 31 if dict == None: 32 return False 33 if self.Name in dict: 34 if dict[self.Name] == self.Password: 35 return True 36 return False 37 38 39 40 def register(self): 41 """ 42 用户注册 43 :return: 44 """ 45 if os.path.exists(self.DIR) != True: 46 os.system('mkdir'+' '+ self.DIR) 47 try: 48 dict = PersonInfo.config_read() 49 if dict == None: 50 dict = {} 51 if self.Name not in dict: 52 dict[self.Name] = self.Password 53 else: 54 print ("姓名重复") 55 return False 56 re = PersonInfo.config_write(dict) 57 if re == True: 58 return True 59 except Exception,e: 60 print "注册出现异常!",e 61 return False 62 63 64 65 def view_file(self,conn): 66 """ 67 查看用户家目录 68 :param conn: 69 :return: 70 """ 71 data = os.popen('ls'+' '+ self.DIR).read() 72 conn.sendall(data) 73 74 def Recvfile(self,conn,filename): 75 """ 76 接收文件方法 77 :param conn:tcp连接对象 78 :param filename:目标文件名 79 :return: 80 """ 81 print ("开始接收文件...") 82 conn.send('Ready!') 83 buffer = [] 84 while True: 85 d = conn.recv(4096) 86 if d == 'exit': 87 break 88 else: 89 buffer.append(d) 90 data = ''.join(buffer) 91 if data == '': 92 return False 93 print (data) 94 print (filename) 95 print (self.DIR) 96 with open(self.DIR + filename, 'w') as f: 97 f.write(data) 98 return True 99 100 101 def Sendfile(self,conn,filename): 102 """ 103 放送文件方法 104 :param conn: tcp连接对象 105 :param filename: 目标文件名 106 :return: 107 """ 108 109 if os.path.exists(self.DIR + filename): 110 print ("开始放送文件...") 111 conn.send('Ready!') 112 time.sleep(1) 113 with open(self.DIR + filename, 'r') as f: 114 while True: 115 data = f.read(4096) 116 print (data) 117 if not data: 118 break 119 conn.sendall(data) 120 time.sleep(1) 121 conn.send('exit') 122 print ("文件放送成功!") 123 else: 124 conn.send('False!') 125 126 127 @staticmethod 128 def config_read(): 129 """ 130 配置文件全部读取 131 :return: 132 """ 133 if os.path.exists(PersonInfo.ConfigDir+'user_config'): 134 with open(PersonInfo.ConfigDir+'user_config','r') as f: 135 dict = pickle.load(f) 136 return dict 137 138 139 @staticmethod 140 def config_write(dict): 141 """ 142 配置文件全部写入 143 :param dict: 144 :return: 145 """ 146 with open(PersonInfo.ConfigDir + 'user_config', 'w') as f: 147 pickle.dump(dict,f) 148 return True
- 客户端:server_client.py
#!usr/bin/env python # -*- coding:utf-8 -*- # auther:Mr.chen # 描述: import socket,os import time TAG =True DIR = os.path.dirname(os.path.abspath(__file__)) DIR = DIR+'/Folder/' HOST = 'localhost' PORT = 8888 def Recvfile(s,filename): """ 接收文件方法函数 :param s: 套接字封装对象 :param filename: 目标文件名 :return: """ print ("开始下载文件...") buffer = [] while TAG: d = s.recv(4096) if d == 'exit': break buffer.append(d) data = ''.join(buffer) with open(DIR+filename,'w') as f: f.write(data) print ("文件下载完毕!") def Sendfile(s,filename): """ 放送文件方法函数 :param s: 套接字封装对象 :param filename: 目标文件名 :return: """ print ("开始上传文件!") if os.path.exists(DIR+filename): with open(DIR+filename,'r') as f: while TAG: data = f.read(4096) if not data: break s.sendall(data) time.sleep(1) s.send('exit') print ("文件上传完毕") else: print ("你的目录里没有这个文件") time.sleep(1) s.send('exit') def Confirm(s,command): """ 验证与服务器连接是否正常; 把用户命令发过去,让服务器做好相应准备准备 :param s: 套接字封装对象 :param command: 用户输入的命令 :return: """ s.sendall(command) re = s.recv(4096) if re == 'Ready!': return True elif re == 'False!': return False else: print ("与服务器连接出现异常!") def File_transfer(s): """ 用户指令函数 :param s: :return: """ while TAG: command = raw_input("请输入你想执行的命令>>") if not command: continue if command.lower().strip() == 'help': print ("请用'put'+'空格'+'文件名'的格式上传文件") print ("请用'get'+'空格'+'文件名'的格式下载文件") print ("输入'ls'查看用户服务器家目录") continue if command.lower().strip() == 'ls': s.send('ls') data = s.recv(4096) print (data) continue try: action,filename = command.strip().split() action = action.lower() except: print ("您的输入有误!输入help查看帮助文档") continue if action == 'put': re = Confirm(s,command) if re == True: Sendfile(s, filename) else: print ("对方服务器没有准备好!") break elif action == 'get': re = Confirm(s,command) if re == True: Recvfile(s, filename) elif re == False: print ("服务器家目录没有这个文件") else: print ("对方服务器没有准备好!") break else: print ("你输入的命令有误!输入help查看帮助文档") def Login(s): """ 用户登录 :param s: :return: """ name = raw_input("请输入你的用户名:") password = raw_input("请输入你的密码:") command = 'login'+' '+ name + ',' + password re = Confirm(s, command) if re == True: print ("登陆成功!") File_transfer(s) elif re == False: print ("您的输入有误,请重新输入!") Login(s) else: print ("与服务器连接出现异常!") def Register(s): """ 用户注册 :param s: :return: """ name = raw_input("请输入你的用户名:") password = raw_input("请输入你的密码:") Password = raw_input("请再次输入密码:") if password != Password: print ("你的密码两次输入不一致,请重新输入!") Register(s) command = 'register' + ' ' + name + ',' + password print (command) re = Confirm(s,command) if re == True: File_transfer(s) elif re == False: print ("用户名重复,请重新输入!") Register(s) else: print ("与服务器连接出现异常!") def Main(s,log = '未联通主机...'): """ 用户登陆界面 :param s: :param log: :return: """ text = """ 用户登陆界面 {0} 1,用户登陆 2,用户注册 """.format(log) print (text) choose = raw_input("请输入索引进行选择:") if choose == '1': Login(s) elif choose == '2': Register(s) else: print ("你的选择有误!") if __name__ == "__main__": s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((HOST,PORT)) Main(s,s.recv(1024)) except Exception,e: print "服务器连接不上....",e finally: s.close()
北京IT职业教育培训中心,欢迎来校咨询。微信号:yinsendemogui(添加时请注明博客园)