requirement :

1. User encryption authentication

2. Multiple users log in at the same time

3. Each user has his own home directory and can only access his own home directory

4. Disk quota for users 、 Different user quotas can be different

5. Users can log in server after , Switchable directory

6. View files in the current directory

7. Upload and download files , To ensure the consistency of documents

8. The actual progress bar in the transmission process

9. Support breakpoint renewal

Path as follows

Code

import socket
import pickle
import hashlib
import sys
import time
import os
A = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class Ftp_client(object):
def __init__(self):
self.client = socket.socket()
def help(self):
'''
To help illustrate
:return:
'''
print(''' Please enter the correct command :
ls: Check the files in the root directory
cd: Toggle directory
download: Download the file
upload: On file
mkdir: Create a new folder
''')
def connet(self, ip, port):
'''
Link server
:param ip:
:param port:
:return:
'''
self.client.connect((ip, port))
data = self.client.recv(1024)
print(data.decode())
self.main()
self.ftp_main()
def login(self):
'''
Sign in
:return:
'''
name = input(' Please enter a name ').lower()
password = input(' Please input a password ')
dict = {'name': name, 'password': password}
self.client.sendall(pickle.dumps(dict))
data = self.client.recv(1024)
print(data.decode())
if data.decode()==' Incorrect input ':
return False
def register(self):
'''
register
:return:
'''
while True:
a = input(' Please enter which type of user to register : 1: Ordinary users ( Available space 10M), 2: VIP user ( You can use 30M)')
if a =='':
space = 10485760
break
elif a== '':
space = 31457280
break
else:
print(' Incorrect input ')
continue
name = input(' Please enter a name ').lower()
pd = input(' Please input a password ')
dict = {'name': name, 'password': pd, 'space': space}
self.client.sendall(pickle.dumps(dict))
data = self.client.recv(1024)
print(data.decode())
if data.decode()== ' User name already exists , Please re-enter ':
return False def main(self):
while True:
a = input(' Please enter 1. The user login 2. User registration 3. sign out ')
if a == '':
self.client.sendall('login'.encode())
res = self.login()
elif a == '':
self.client.sendall('register'.encode())
res = self.register()
elif a == '':
exit()
else:
print(' Incorrect input ')
continue
if res is False:
continue
else:
break def download(self):
'''
download
:return:
'''
while True:
data = self.client.recv(1024)
choose = input(' File path 1 root directory 2 subdirectories ')
if choose == '':
path = ''
break
elif choose =='':
path = input(' Please enter the path , The subpath uses / Separate... Separate ') # The root directory doesn't need to be typed
break
else:
print(' Incorrect input ')
continue
self.client.sendall(path.encode())
data = self.client.recv(1024)
filename = input(' Please enter the download file name ')
self.client.sendall(filename.encode())
size = self.client.recv(1024).decode()
if size == ' The file does not exist ':
print (' The file does not exist ')
return False
else:
size = int(size)
if os.path.exists(os.path.join(A, 'db', filename)):
r_size = int(os.path.getsize(os.path.join(A, 'db', filename)))# There is a file of size
while True:
choose = input(' file already exist , 1 Re Download 2 Stop downloading 3 New name and download 4 Continue downloading ')
if choose == '':
dic={}
dic['choose'] = choose
self.client.sendall(pickle.dumps(dic))
return False
elif choose == '':
f = open(os.path.join(A, 'db',filename),'wb')
r_size = 0
break
elif choose == '':
name = input(' Please enter a new file name ')
f = open(os.path.join(A, 'db',name),'wb')
r_size = 0
break
elif choose == '':
f = open(os.path.join(A, 'db',filename),'ab')
break
else:
print(' Incorrect input , Please re-enter ')
dic={}
dic['choose'] = choose
dic['size'] = r_size
self.client.sendall(pickle.dumps(dic))
else:
r_size = 0
f = open(os.path.join(A, 'db', filename),'xb') if size == 0:
f.close()
print(' Completion of reception ')
else:
while r_size < size:
file = self.client.recv(1024)
f.write(file)
f.flush() # File forced write file, Prevent interruptions
r_size += len(file)
view_bar(r_size, size)
time.sleep(0.1)
else:
print(' Completion of reception ')
f.close() def upload(self):
filename = input(' Please enter the name of the uploaded file ')
if os.path.exists(os.path.join(A, 'db', filename)):
size = os.path.getsize(os.path.join(A, 'db', filename)) # file size
path = input(' Please enter the upload path , The subpath uses / Separate... Separate , h For root ')
dic = {}
dic['filename'] = filename
dic['size'] = size
dic['path'] = path
self.client.sendall(pickle.dumps(dic))
f = open(os.path.join(A, 'db', filename), 'rb')
else:
print (' This file does not exist ')
return False
data = self.client.recv(1024)
ls = pickle.loads(data) #ls[2]: ;
if ls[-1]=='': #ls[-1]: Check if the download path exists
print (' This path does not exist ')
return False
if ls[0] == '':#ls[0]: Check if there's enough space ;
print (' The space is insufficient , Can't upload ') else:
if ls[1] == '': #ls[1]: Check if the download exists
while True:
a = input(' file already exist , 1 Re Download 2 Stop downloading 3 New name and download 4 Continue downloading ')
f_ls = []
f_ls.append(a)
if a == '':
break
elif a == '':
return False
elif a =='':
f_name = input(' Please enter a new file name ')
f_ls.append(f_name)
break
elif a=='':
l_size = ls[2] #ls[2]: Size of downloaded files
f.seek(l_size) # Put the pointer where it has been downloaded , Continue downloading
break
else:
print (' Incorrect input ')
else:
f_ls = []
f_ls.append('') # 5: Download file does not exist
self.client.sendall(pickle.dumps(f_ls))
data = self.client.recv(1024).decode()
print (data)
for line in f:
self.client.sendall(line)
num = f.tell() # Check the file upload location
view_bar(num, size)
time.sleep(0.1)
f.close()
print (' Completion of reception ')
return False def ls(self):
data = self.client.recv(1024)
if data ==''.encode():
print(' This directory is empty ')
elif data ==''.encode():
print(' This file does not exist ')
else:
ls = pickle.loads(data)
print(' This document contains :')
for i in ls:
print(i) def mkdir(self):
name = input(' Please enter a folder name ')
self.client.sendall(name.encode())
data = self.client.recv(1024).decode()
print(data) def cd(self):
name = input(' Please enter the path , The subpath uses / Separate... Separate ') # The root directory doesn't need to be typed
self.client.sendall(name.encode())
path = self.client.recv(1024).decode() if path == '':
print (' This directory does not exist ')
return False
else:
print (' The folder path is %s' % path)
self.client.sendall('ok'.encode())
data = self.client.recv(1024)
if data ==''.encode():
print(' This directory is empty ')
else:
ls = pickle.loads(data)
print(' This document contains :')
for i in ls:
print(i) def ftp_main(self):
while True:
a = input(' Please input the corresponding instruction , help: Inquire about , exit: sign out ')
if hasattr(self, a):
self.client.sendall(a.encode())
func = getattr(self, a)
func()
elif a == 'exit':
exit()
else:
self.help()
continue def view_bar(num, total):
''' Progress bar '''
rate = float(num) / float(total)
rate_num = int(rate * 100)
r = '\r%d%%' % (rate_num, ) #\r Back to the beginning
sys.stdout.write(r)
sys.stdout.flush() # Delete record ftp = Ftp_client()
ftp.connet('localhost', 9999)

client

import socketserver
import pickle
import os
import time
A = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
self.request.sendall(' Link successful '.encode())
while True:
data = self.request.recv(1024).decode()
if data =='login':
a = self.login()
else:
a = self.register() #a by list,[0] yes name,[1] It's available space
if a is False:
continue
else:
while True:
data = self.request.recv(1024)
func = getattr(self, data.decode())
func(a)
except Exception: # Check whether the client connection is normal
print(' Client disconnected ')
break def login(self):
db_dict = pickle.load(open(os.path.join(A, 'db', 'register'),'rb'))
self.data = self.request.recv(1024)
dict = pickle.loads(self.data)
if dict['name'] in db_dict:
if dict['password']==db_dict[dict['name']][0]:
self.request.sendall(' Login successful '.encode())
return [dict['name'], db_dict[dict['name']][1]] # Return user name , User free space
else:
self.request.sendall(' Incorrect input '.encode())
return False
else:
self.request.sendall(' Incorrect input '.encode())
return False
def register(self):
dict = pickle.loads(self.request.recv(1024))
print (dict)
if os.path.exists(os.path.join(A, 'db', dict['name'])):
self.request.sendall(' User name already exists , Please re-enter '.encode())
return False
else:
self.request.sendall(' Registered successfully '.encode())
os.makedirs(os.path.join(A, 'db', dict['name']))
# n_dict ={}
n_dict = pickle.load(open(os.path.join(A, 'db', 'register'), 'rb'))
print (1)
print (n_dict)
n_dict[dict['name']]=[dict['password'],int(dict['space'])] # The storage format is { full name :[ password , How much space is available ]}
print (n_dict)
pickle.dump(n_dict,open(os.path.join(A, 'db', 'register'), 'wb'))
return [dict['name'], int(dict['space'])]
def help(self, a):
return False
def upload(self, list):
name = list[0]
b_path = os.path.join(A, 'db', name) # Your own root directory
h_size = int(list[1]) # The amount of space you can use
data = self.request.recv(1024)
dic = pickle.loads(data)
f_size = int(dic['size']) # Upload file size
filename = dic['filename']
path = dic['path']
s_ls = []
if h_size < f_size:
a = '' # The space is insufficient
s_ls.append(a)
else:
a = ''
s_ls.append(a)
if path=='h': # There is a root directory
l_path =os.path.join(b_path,filename)
else:
res = path.split('/')
print (res)
for i in res:
b_path = os.path.join(b_path, i) # Put together a subdirectory
l_path = os.path.join(b_path,filename) # File path if os.path.exists(l_path):
b = '' # file already exist
file_size = os.path.getsize(l_path)
s_ls.append(b)
s_ls.append(file_size)
else:
b = ''
s_ls.append(b)
if os.path.exists(b_path):
c = ''
else:
c=''# Folder does not exist , Can end
s_ls.append(c)
self.request.sendall(pickle.dumps(s_ls))
return False
s_ls.append(c)
self.request.sendall(pickle.dumps(s_ls))
f_ls = pickle.loads(self.request.recv(1024))# How does the file open
self.request.sendall(' Get ready to start '.encode())
if f_ls[0] =='':
f = open(l_path,'wb')
file_size = 0
elif f_ls[0]=='':
return False
elif f_ls[0]=='':# The file name is different
filename = f_ls[1]
l_path = os.path.join(b_path,filename)
f = open(l_path,'wb')
file_size = 0
elif f_ls[0]=='':
f = open(l_path,'ab')
else:
f = open(l_path,'xb')
file_size = 0
if f_size == 0:
f.close()
return False
else:
while file_size< f_size:
line = self.request.recv(1024)
f.write(line)
f.flush()
file_size += len(line)
else:
f.close()
l_dict = pickle.load(open(os.path.join(A, 'db', 'register'), 'rb'))
l_dict[name][1] = h_size - f_size # Modify used space
pickle.dump(l_dict, open(os.path.join(A, 'db', 'register'), 'wb'))
return False def download(self, list):
self.request.sendall('ok'.encode())
path = self.request.recv(1024).decode() # Check that the file has a subdirectory or root
self.request.sendall('check'.encode())
filename = self.request.recv(1024).decode()
name = list[0]
if path == '':
l_path = os.path.join(A, 'db', name,filename)
else:
data = path.split('/')
pathname = os.path.join(A, 'db', name)
for i in data:
pathname = os.path.join(pathname, i) # Collage subdirectories
l_path = os.path.join(pathname,filename)
print (l_path)
if os.path.exists(l_path):
f = open(l_path, 'rb')
size = os.path.getsize(l_path) # Check the documents
self.request.sendall(str(size).encode()) # To pass numbers in string format
data = self.request.recv(1024)
dic = pickle.loads(data)
if dic['choose']=='':
return False
elif dic['choose']=='':
f.seek(int(dic['size'])) # Locate the pointer where it has been downloaded
for line in f:
self.request.sendall(line)
f.close()
print ('done')
else:
self.request.sendall(' The file does not exist '.encode()) def ls(self, list):
name = list[0]
ls = os.listdir(os.path.join(A, 'db', name))
if len(ls)==0:
self.request.sendall(''.encode())
else:
a = []
for i in ls:
a.append(i) # Put the existing files in list
self.request.sendall(pickle.dumps(a))
def cd(self, list):
data = self.request.recv(1024).decode()
name = list[0]
path = os.path.join(A, 'db', name) # root directory
path_ls = data.split('/')
for i in path_ls:
path = os.path.join(path, i) # Collage subdirectories
print (path)
if os.path.exists(path) is False:
print (1)
path = ''
self.request.sendall(path.encode())
return False
ls = os.listdir(path)
self.request.sendall(path.encode())
data = self.request.recv(1024)
if len(ls)==0:
self.request.sendall(''.encode())
else:
a = []
for i in ls:
a.append(i)
self.request.sendall(pickle.dumps(a)) def mkdir(self, a):
filename = self.request.recv(1024).decode()
name = a[0]
if os.path.exists(os.path.join(A, 'db', name,filename)): # Check if the path exists
self.request.sendall(' Folder already exists '.encode())
else:
os.makedirs(os.path.join(A, 'db', name, filename))
self.request.sendall(' Built '.encode()) host, port = 'localhost', 9999
server = socketserver.ThreadingTCPServer((host, port), MyTCPHandler)
server.serve_forever()

server

senior FTP More articles on server development

  1. Python09 Homework ideas and source code : senior FTP Server development ( For reference only )

    senior FTP Server development One , Job requirements senior FTP Server development User encryption authentication ( complete ) Multiple users log in at the same time ( complete ) Each user has a different home directory and can only access their own home directory ( complete ) Disk quota for users , Different user quotas can be different ( complete ...

  2. python Day 48 -- senior FTP

    senior FTP The server 1. User encryption authentication 2. Multiple users log in at the same time 3. Each user has his own home directory and can only access his own home directory 4. Disk quota for users . Different user quotas can be different 5. Users can log in server after , Switchable directory 6. check ...

  3. ( turn )python senior FTP

    Original address :http://www.itnose.net/detail/6754889.html senior FTP The server 1. User encryption authentication 2. Multiple users log in at the same time 3. Each user has his own home directory and can only access his own home directory 4. ...

  4. Utilities Commer Development of ——U Disk content can be synchronized to FTP The server

    Demand analysis : Need to be inserted after the software runs U The files in the disk Copy To the machine , Then you can upload part of it to FTP Server . The system design : be based on MFC The basic dialog program : The main modules are detection U Disk insert and copy files and upload to the network . Through to U ...

  5. Develop a thread based FTP The server

    One , Project title : Develop a thread based FTP The server Two , Project requirement : The basic requirements : 1. User encryption authentication   2. Allow multiple users to log in at the same time   3. Each user has his own home directory , You can only access your home directory   4. Disk configuration for users ...

  6. python Development ftp The first day of the server (pyftpdlib)

    I've been studying for about a month python, Now start consciously doing some projects .( My new book <Python Reptile development and project practice > Published , You can take a look at the sample chapter ) As far as I know ,python Now it's more used in automatic operation and maintenance , ...

  7. FTP Server advanced configuration

    Set up FTP Server access restrictions /etc/vsftpd/ftpusers ftpusers : The blacklist All users in it cannot log in FTP The server If userlist_enable=YES( Set... In the main configuration file ),u ...

  8. python Homework advanced FTP

    Reprinted from :https://www.cnblogs.com/sean-yao/p/7882638.html Job requirements : 1. User encryption authentication 2. Multiple users log in at the same time 3. Each user has his own home directory and can only access himself ...

  9. python Homework advanced FTP( Week eight )

    Job requirements : 1. User encryption authentication 2. Multiple users log in at the same time 3. Each user has his own home directory and can only access his own home directory 4. Disk quota for users . Different user quotas can be different 5. Users can log in server after , Switchable directory 6 ...

Random recommendation

  1. bzoj 2244: [SDOI2011] Interceptor missile cdq Divide and conquer

    2244: [SDOI2011] Interceptor missile Time Limit: 30 Sec  Memory Limit: 512 MBSec  Special JudgeSubmit: 237  Solved: ...

  2. android3.2 It is forbidden to cut the screen above onCreate()

    Generally, screen switching is prohibited onCreate() The method needs to put activity Add attributes : android:configChanges=”orientation|keyboardHidden” But in 3.2 That doesn't work ...

  3. Angular2.js—— Master-slave structure

    Learn the content of this article , Back to our fast start applications . Master-slave structure , We want to make a list of Heroes , We want users to select a hero in the list , Then the selected hero appears in the details view . The main view is the list of Heroes , From the view is the details of the selected hero ...

  4. modify node To add custom tool commands

    How to use node Create custom cmd command One . The realization of command function 1. Put the folder of your own custom tools in the currently used node Under the installation directory of node_modules Under the folder : 2. go back to node Copy from the installation directory ...

  5. web、pc、wap、app The difference between

    Usually web=pc,wap=app, The former refers to the program used by the computer , The latter refers to the program used by the mobile phone . The deeper difference is ,pc Software on the computer ,web Web pages on the computer ,wap Web pages on mobile phones ,app Mobile Software

  6. linux Command to free memory

    Release cache: sync echo 3>/proc/sys/vm/drop_caches Release swap: sync swapoff -a swapon -a Copyright notice : This article is an original blog article , without ...

  7. 【php】 Download Station System Simple Down v5.5.1 xss Cross site vulnerability analysis

    author:zzzhhh One .         Cross site loopholes Utilization method 1, Search directly in the search box <script>alert(/xss/)</script>//', Refresh again , Cross site statements will be ...

  8. mysql week How to use

    mysql week How to use , Details please see : https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function ...

  9. PHP Study type Variable constant Operator

    PHP Support the following 8 Types Scalar type scalar type Integers integer Floating point numbers float double Boolean boolean character string string Special type special typeNULL resources r ...

  10. 【 The front-end development 】localStorage Usage of

    localStorage.setItem("name","value")  // Storage name Value var type = localStorage.getItem ...