开发简单的FTP:
1. 用户登陆
2. 上传/下载文件
3. 不同用户家目录不同
4. 查看当前目录下文件
5. 充分使用面向对象知识

REDMAE

 1 用户登陆2 3 1、查看用户目录文件4 2、上传文件,5 3、下载方件6 4、退出7 8 程序结构:9 socket_server_client/#程序目录
10 |- - -clients/#client程序主目录
11 |      |- - -__init__.py
12 |      |- - -bin/#启用目录
13 |      |       |- - - __init__.py
14 |      |       |- - -socket_client.py#客户端启动
15 |      |
16 |      |- - -cfg/#配置文件目录
17 |      |       |- - - __init__.py
18 |      |       |- - -config.py#配置文件
19 |      |
20 |      |- - -core/#主要程序目录
21 |      |       |- - - __init__.py
22 |      |       |- - -client_func.py#主要函数
23 |      |
24 |      |- - -home/#客户端下载文件目录
25 |
26 |- - -servers/#server程序主目录
27 |      |- - -__init__.py
28 |      |- - -bin/#启用目录
29 |      |       |- - - __init__.py
30 |      |       |- - -registration.py#用户注册
31 |      |       |- - -socket_server.py#服务端启动
32
33 |      |
34 |      |- - -cfg/#配置文件目录
35 |      |       |- - - __init__.py
36 |      |       |- - -config.py#配置文件
37 |      |
38 |      |- - -core/#主要程序目录
39 |      |       |- - - __init__.py
40 |      |       |- - -server_classc.py#主要函数
41 |      |
42 |      |- - -db/#用户上传文件主目录
43 |              |- - -user_file/#用户上传目录
44 |              |- - -user_names#注册用户文件
45 |

服务端

servers/

    bin/

registration.py

 1 #!usr/bin/env python2 #-*-coding:utf-8-*-3 # Author calmyan4 import socket,os,json,sys,pickle5 6 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量7 sys.path.append(BASE_DIR)#增加环境变量8 from cfg import config9 print('用户注册'.center(60,'='))
10 while True:
11     user_=input('请输入您要注册的用户名:').strip()
12     user_dir=os.path.join(config.USER_DIR,user_)#拼接用户目录路径
13     if os.path.isdir(user_dir):# 判断一个目录是否存在
14         print('用户已经存在请重输!')
15         continue
16     else:
17         pwd_=input('请输入密码:').strip()
18         pwd_two=input('请确认密码:').strip()
19         if pwd_==pwd_two:
20             try:
21                 os.mkdir(user_dir)#创建目录
22             except Exception as e:
23                 print(e)
24                 continue
25             finally:
26                 file_dir=user_dir+'\\user'#用户目录下的用户名文件
27             if  not os.path.isfile(config.USER_FILE):
28                 with open(config.USER_FILE,'w',encoding='utf-8') as f:
29                     f.write('{}')
30             with open(config.USER_FILE,'r+',encoding='utf-8') as f:
31                 data=eval(f.readline())
32                 data[user_]=pwd_
33                 f.seek(0)
34                 f.write(str(data))
35             print('用户[%s]注册成功!'%user_)
36             exit()

socket_server.py

 1 #!usr/bin/env python2 #-*-coding:utf-8-*-3 # Author calmyan4 import socket,os,json5 import sys6 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量7 sys.path.append(BASE_DIR)#增加环境变量8 9 from  core.server_class import listen_func
10 s=socket.socket()#定义
11 s.bind(('localhost',9000))#绑定要监听的 端口
12 s.listen(5)#对列5
13 print('正在监听中')
14 listen_func(s)

cfg/

config.py

 1 #!usr/bin/env python2 #-*-coding:utf-8-*-3 # Author calmyan4 import os ,sys5 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量6 sys.path.append(BASE_DIR)#增加环境变量7 8 9 USER_DIR=BASE_DIR+'\db\\user_file\\'#定义用户目录文件路径变量
10
11 USER_FILE=BASE_DIR+'\db\\user_names'#定义用户文件路径变量

core/

server_class.py

  1 #!usr/bin/env python2 #-*-coding:utf-8-*-3 # Author calmyan4 import socket,os,json,sys,pickle5 6 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量7 sys.path.append(BASE_DIR)#增加环境变量8 9 from cfg import config10 11 12 #用户名检测函数13 def open_file_list(name,pas):#传入当前类14     with open(config.USER_FILE,'r',encoding='utf-8') as f:15         data=eval(f.readline())16         if name in data and pas==data[name]:17             return True18         else:19             return False20 21 22 #连接类23 class socket_server(object):24     '''连接类'''25     file_path=config.USER_DIR#用户路经变量26     def __init__(self,data,conn):#传入用户名,密码27         self.DATA=data28         self.conn=conn29 30 31     def show_process(self,lens):32         received_size=0#定义大小33         current_percent=0#当前大小百分比34         while received_size<lens:35             if int((received_size/lens)*100)>current_percent:36                 print('#',end='',flush=True)37                 current_percent=int((received_size/lens)*100)38             new_size=yield39             received_size+=new_size40 41     def ret_l(self):42         ret=socket_server.login(self.DATA["name"],self.DATA['pwd'],self.conn)#用户名检测43         return ret44     def open_f(self,ret):#打开目录45         file_dir=os.path.join(socket_server.file_path,ret['data']['user'])#用户目录46         file_name=os.listdir(file_dir)#目录文件列表47         f=file_dir+self.DATA['filename']##上传的文件名48         return file_dir,file_name,f#返回49 50     def ls_file(self,data):#查看文件51         self.conn.send(json.dumps(data[1]).encode())52 53     def send_file(self,data):54 55         if self.DATA['filename'] in data[1]:56             f=data[0]+'/'+self.DATA['filename']57             file_obj=open(f,"rb")#打开文件58             name=file_obj.name.split('/')[-1]#文件名59             sez=os.path.getsize(f)#获取文件大小60             print(sez)61             data_header={62                     "action":"put",63                     "filename":name,64                     "size":sez65                     }66             self.conn.send(json.dumps(data_header).encode())#用json 序列化后,发送相关 信息67             for line in file_obj:68                 self.conn.send(line)#发送数据69 70         elif self.DATA['filename'].isdigit():71             num=int(self.DATA['filename'])#转为数字72             try:73                 f=data[0]+'/'+data[1][num]#74                 file_obj=open(f,"rb")#打开文件75                 name=file_obj.name.split('/')[-1]#文件名76                 sez=os.path.getsize(f)#获取文件大小77                 print(sez)78                 data_header={79                 "action":"put",80                 "filename":name,81                 "size":sez82                 }83                 self.conn.send(json.dumps(data_header).encode())#用json 序列化后,发送相关 信息84                 for line in file_obj:85                     self.conn.send(line)#发送数据86                 self.conn.send(json.dumps(f).encode())#发送文件87             except Exception as e:88                 data={'filename':False}89                 self.conn.send(json.dumps(data).encode())90         else:91             data={'filename':False}92             self.conn.send(json.dumps(data).encode())93     def put_file(self,data):#上传文件94         file_obj=open(data[2],'wb')#打开新建 这个文件95         rece_size=0#定义 文件大小值96         #prten=socket_server.show_process(self.DATA["size"])97         #prten.__next__()98         while rece_size<self.DATA["size"]:#小于接收的文件大小时,99             recv_data=self.conn.recv(4096)
100             file_obj.write(recv_data)#写入文件
101             rece_size+=len(recv_data)#增加文件大小计算
102
103         else:
104             print("文件[%s]接收完毕!"%self.DATA["filename"])
105             file_obj.flush()
106             file_obj.close()#关闭文件
107
108
109     @staticmethod
110     def login(name,pas,conn):#用户检测 函数
111         try:
112             if open_file_list(name,pas):
113                 tag=True
114                 error=''
115                 datas={'user':name}
116                 data={'mag':'用户认证通过','tag':True}
117                 print(json.dumps(data).encode())
118                 conn.send(json.dumps(data).encode())
119             else:
120                 raise Exception('\033[41;1m用户名或密码错误\033[0m' %name)
121         except Exception as e:
122             tag=False
123             error=str(e)
124             datas=''
125             data={'mag':'用户或密码错误','tag':False}
126             print('发送数据%s'%data)
127             conn.send(json.dumps(data).encode())
128         return {'tag':tag,'error':error,'data':datas}
129
130 #监听函数
131 def listen_func(s):
132     while True:
133         conn,client_addr=s.accept()#端口监听中....返回两个值 ,联接编号对象 , ip
134         print('获取到新连接:',client_addr)
135         while True:
136             data=conn.recv(4096)#接收数据 指令
137             print('接收的数据:',data)
138             data= json.loads(data.decode())#反序列
139             if len(data)==0:
140                 break
141             if data['action']=='user':#如果是用户名,进行认证\
142                 serv=socket_server(data,conn)
143                 ret=serv.ret_l()
144             if ret['tag']:
145                 pass
146             else:
147                 continue
148
149             print(data)
150             if data['action']=="put":#如果接收的字典中是put,就是进行接收
151                 serv=socket_server(data,conn)
152                 serv.put_file(serv.open_f(ret))#调对象方法
153             elif data['action']=='get':#下载
154                 serv=socket_server(data,conn)#实例化
155                 serv.send_file(serv.open_f(ret))#调 用方法
156             elif data['action']=='ls':#查看
157                 serv=socket_server(data,conn)
158                 serv.ls_file(serv.open_f(ret))
159                 continue

客户端

clients/

bin/

socket_client.py

  1 #!usr/bin/env python2 #-*-coding:utf-8-*-3 # Author calmyan4 5 import socket,os,json,sys6 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量7 sys.path.append(BASE_DIR)#增加环境变量8 from core.client_func import user_pwd9 #from core.client_func import show_process10 from cfg import config11 12 #进度条13 def show_process(lens):14     received_size=0#定义大小15     current_percent=0#当前大小百分比16     while received_size<lens:17         if int((received_size/lens)*100)>current_percent:18             print('#',end='',flush=True)19             current_percent=int((received_size/lens)*100)20         new_size=yield21         received_size+=new_size22 23 24 client=socket.socket()25 client.connect(('localhost',9000))26 while True:27     data_d=user_pwd(client)28     if data_d['tag']:#运行#用户名登陆成功29         while True:30             print('''=====指令提示====31             查看目录文件: ls32             下载文件: get 文件名 或 文件编号  如: get test.txt  或  get 133             上传方件: put 路径/文件名 如 put e:/test.txt34             退出:exit35             ''')36             cho=input('指令 >>:').strip()37             if len(cho)==0:continue38             if cho=='exit':exit()#退出指令39             cmd_list=cho.split()40             if cmd_list[0]=='put':#如果等于下载指令41                 if len(cmd_list)==1:42                     print('没有输入相关文件名')43                     continue44                 filename=cmd_list[1]45                 if os.path.isfile(filename):#如果文件存在46                     file_obj=open(filename,"rb")#打开文件47                     name=file_obj.name.split('/')[-1]#文件名48                     #name=filename.split("\\")[-1]#文件名49                     sez=os.path.getsize(filename)#获取文件大小50                     data_header={51                         "action":"put",52                         "filename":name,53                         "size":sez54                     }55                     client.send(json.dumps(data_header).encode())#用json 序列化后,发送相关 信息56 57                     print("文件[%s]发送中...."%data_header["filename"])58                     for line in file_obj:59                         client.send(line)60                     else:61                         print("文件[%s]发送完毕!"%data_header["filename"])62                 else:63                     print('该文件不存在')64                     continue65             elif cmd_list[0]=='get':#如查等 于上传指令66                 if len(cmd_list)==1:67                     print('没有输入相关文件名')68                     continue69                 filename=cmd_list[1]70                 print(filename)71                 data_header={72                         "action":"get",73                         "filename":filename,74                         "size":''75                     }76                 client.send(json.dumps(data_header).encode())#用json 序列化后,发送相关 信息77                 datas=client.recv(4096)#接收数据 指令78                 data_l= json.loads(datas.decode())#反序列79                 if  not data_l['filename']:80                     print('文件不存在')81                     continue82                 file_dir=config.USER_DIR+data_l["filename"]83                 file_obj=open(file_dir,'wb')#打开新建 这个文件84                 rece_size=0#定义 文件大小值85                 prten=show_process(data_l["size"])86                 prten.__next__()87                 while rece_size<data_l["size"]:#小于接收的文件大小时,88                     recv_data=client.recv(4096)89                     file_obj.write(recv_data)#写入文件90                     rece_size+=len(recv_data)#增加文件大小计算91                     try:92                         prten.send(len(recv_data))93                     except StopIteration as e:94                         print('100%')95 96                 else:97                     print("文件[%s]接收完毕!"%data_l["filename"])98                     file_obj.flush()99                     file_obj.close()#关闭文件
100             elif cmd_list[0]=='ls':#查看目录文件
101                 data_header={
102                         "action":"ls",
103                         "filename":'',
104                         "size":''
105                     }
106                 client.send(json.dumps(data_header).encode())#用json 序列化后,发送相关 信息
107                 datas=client.recv(4096)#接收数据 指令
108                 data_l= json.loads(datas.decode())#反序列
109                 for k,v in enumerate(data_l):
110                     print('编号: %s  文件名:%s'%(k,v))
111
112     else:
113         print(data_d['mag'])

cfg/

config.py

 1 #!usr/bin/env python2 #-*-coding:utf-8-*-3 # Author calmyan4 5 import os ,sys6 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量7 sys.path.append(BASE_DIR)#增加环境变量8 9
10 USER_DIR=BASE_DIR+'\home\\'#定义用户目录文件路径变量

core/

client_func.py

 1 #!usr/bin/env python2 #-*-coding:utf-8-*-3 # Author calmyan4 import socket,os,json,sys5 #用户名登陆函数6 def user_pwd(client):7     user_=input('请输入用户名:').strip()8     pwd_=input('请输入密码:').strip()9     data_header={
10                 "action":"user",
11                 "name":user_,
12                 "pwd":pwd_
13             }
14     client.send(json.dumps(data_header).encode())#用json 序列化后,发送相关 信息
15     data=client.recv(4096)#接收数据 指令
16     data_s=json.loads(data.decode('utf-8'))#反序列
17     return data_s
18
19
20 #进度条
21 def show_process(lens):
22     received_size=0#定义大小
23     current_percent=0#当前大小百分比
24     while received_size<lens:
25         if int((received_size/lens)*100)>current_percent:
26             print('#',end='',flush=True)
27             current_percent=int((received_size/lens)*100)
28         new_size=yield
29         received_size+=new_size

转载于:https://www.cnblogs.com/xiaohuamao/p/7003830.html

转载别人的ftp,觉得目录结构不错,学习相关推荐

  1. python打印目录结构_Python学习笔记(2)——遍历目录结构并打印

    有时候想看一下项目中的目录和文件结构,用python实现 主要用到这几个函数 import os os.getcwd()  #获取当前运行程序的目录 os.listdir(path) #取得path下 ...

  2. linux中的目录结构---Linux学习笔记

    系统目录的解释: /home:普通用户的家目录,每个用户在该目录下都有一个与用户名同名的目录 /root:超级用户root的家目录/bin:普通用户的可执行命令,系统的任何用户都可以执行该目录中的命令 ...

  3. 【Django】基于Django架构网站代码的目录结构---转载

    经典的Django项目源码目录结构 Django在一个项目的目录结构划分方面缺乏必要的规范.在Django的官方文档中并没有给出大型项目的代码建议目录结构,网上的文章也是根据项目的不同结构也有适当的变 ...

  4. linux ftp日志_linux学习笔记(一)——Linux分区和目录结构

    linux学习笔记(一)--Linux分区和目录结构 安装Linux时,手动挂载分区的情况下,/ 和 swap 是必须要挂载的,其他/home./boot 等可以根据需要自行挂载. 一般来说,简单的话 ...

  5. 【Vue】Vue-cli(脚手架)的目录结构详解(转载)

    一.图简单说明下各个目录都是干嘛的: 总体框架:一个vue-cli的项目结构如下,其中src文件夹是需要掌握的,所以本文也重点讲解其中的文件,至于其他相关文件,了解一下即可. 四.文件结构细分 1.b ...

  6. 【转载】Unix设计哲学 回车换行八卦 EOF八卦 UNIX目录结构八卦

    昨天看了这篇文章 <关于Unix哲学> 首先用了两个例子,用风扇吹出空肥皂盒 和 太空铅笔,来说明简单设计也能派上作用吧. Unix哲学,Wikipedia上列出了好几个版本,不同的人有不 ...

  7. CentOS目录结构超详细版

    最近初学Linux 对linux的目录产生了很多疑问,看到这篇文章,让我顿时对目录有了一个清晰的认识!推荐给大家! ------------------------------------------ ...

  8. linux目录结构   各个目录文件作用

     linux 目录结构 /: 根目录,一般根目录下只存放目录,不要存放文件,/etc./bin./dev./lib./sbin应该和根目录放置在一个分区中 /bin:/usr/bin: 可执行二进制文 ...

  9. linux闲话FHS标准下linux目录结构

    2019独角兽企业重金招聘Python工程师标准>>> 1.闲话         2011年10月24日收到了秒针的OfferLetter并决定加入之后,就开始认真学习linux.坦 ...

最新文章

  1. bartlett方差齐性检验_R语言实用教程-数据正态性以及方差齐性检验
  2. 提高github下载速度
  3. 【IT笔试面试题整理】堆栈和队列
  4. 怎样查看Jdk是32位还是64位
  5. SpringBoot : 注解@Resource
  6. 高斯金字塔 matlab,图像拼接中 高斯金字塔的建立 matlab程序详细解释 现金奖励...
  7. 位运算(异或运算) :数组中数字出现的次数
  8. 2021考研——复习规划(数学篇)
  9. 单片机支持EM4100和T5577两种ID门禁卡
  10. JAVA UrlRewrite 使用教程与注意点,JAVA 实现伪静态,URLRewrite实现url地址伪静态化,springboot中url地址重写(urlwrite),jeesite4伪静态
  11. 9大日常不良习惯致癌
  12. 2021 新款手机,免费送!
  13. 力扣 2042检查句子中地数字是否递增
  14. OpenGL---GLUT教程(二) GLUT初始化
  15. 华为nova8pro和小米11哪个好
  16. emd分解详解一种自适应的数据处理或挖掘方法
  17. Android之查看Wifi密码
  18. 如果使用Qt来开发商业软件,是否需要付费?
  19. STKO助力OpenSEES系列:平面多层多跨混凝土框架静力循环pushover分析
  20. 词频统计(python)

热门文章

  1. 智慧城市炫酷效果、threejs绘制道路、TubeGeometry实现道路流光效果
  2. springMVC同时支持跳转jsp和html
  3. vue2关于EventBus使用
  4. Java多线程:线程间通信方式
  5. iOS开发 - 在实战中挖掘之线程间的通信方式
  6. VScode无法单步调试python
  7. 使您的软件运行起来: 防止缓冲区溢出(转)
  8. vue脚手架的搭建以及element的搭建 ---冯浩的博客
  9. dede后台登陆又返回登陆界面怎么办
  10. 三星Samsung CLX-3175FW 驱动