天天看點

開發一個支援多使用者線上的FTP程式

一,項目題目:開發一個支援多使用者線上的FTP程式

二,項目要求:

1.使用者加密認證

2.允許同時多使用者登入

3.每個使用者有自己的家目錄 ,且隻能通路自己的家目錄

4.對使用者進行磁盤配額,每個使用者的可用空間不同

5.允許使用者在ftp server上随意切換目錄

6.允許使用者檢視目前目錄下檔案

7.允許上傳和下載下傳檔案,保證檔案一緻性(md5)

8.檔案傳輸過程中顯示進度條

9.附加功能:支援檔案的斷點續傳
      

三,注意事項: 

基本要求. 完成1,2,3,5,6,7,8 
實力選手. 完成 上條 及需求4 ,     
大神操作. 完成 9 且項目目錄結構良好、代碼邏輯清晰,
      

  

四,項目分析:

1,使用者加密認證

  這個肯定需要用到configparser 和hashlib子產品,用md5進行加密,服務端與使用者端
進行互動前,肯定需要進行認證,在服務端進行認證,用戶端需要發送使用者名及密碼,但
是為了安全起見,服務端資料庫中的密碼應該是加密後的密文,用戶端登陸認證時也應該
發送密文到服務端,服務端接受到密文與資料庫中對應的密文進行比較。
      

2,檢視自己的目前目錄下的檔案

  這個隻需要寫一個dir就ok
簡單的說,使用configparse子產品就可以完成
      

3,檔案傳輸中顯示進度條

  下載下傳的進度條比較好實作,我們可以從服務端受到将要下載下傳的檔案的大小,

  上傳的進度條,我們可以利用檔案操作的tell()方法,擷取目前指針位置(位元組)
      

4,小編的主要思路

- 1 對于此項目,最初的想法是寫出上傳,和下載下傳檔案的程式,包括用戶端和服務端。

-  2 在此基礎上擴充程式,包括提出開始程式到bin裡面,配置檔案在config裡面

-  3 然後把上傳檔案和下載下傳檔案的程式進行斷點續傳的程式重構

-   4 在此基礎上,對檔案進行加密

-   5 增加功能,包括設定進度條,增加檢視功能,增加目錄功能,删除檔案功能,切換目錄功能等

-   6 然後再設定磁盤配置設定功能,完善内容

-   7 然後添加使用者登陸,包括對使用者的密碼加密等功能

-   8 寫完後檢查程式
      

 五,項目流程圖

開發一個支援多使用者線上的FTP程式

六,README檔案

## 作者:zhanzhengrecheng
## 版本:示例版本 v0.1
## 程式介紹:
- 實作了支援多使用者線上的FTP程式 常用功能
- 功能全部用python的基礎知識實作,用到了socket\hashlib\configparse\os\sys\pickle\函數\子產品\類知識

## 概述
本次作業檔案夾一共包含了以下5個檔案:
- 流程圖: FTP_homework思路流程圖
- 程式結構圖:整個FTP_homework的程式檔案結構
- 程式結構檔案:整個FTP_homework的程式檔案結構
- 程式檔案: FTP_homework
- 程式說明檔案:README.md

## 程式要求
- 1.使用者加密認證
- 2.允許同時多使用者登入
- 3.每個使用者有自己的家目錄 ,且隻能通路自己的家目錄
- 4.對使用者進行磁盤配額,每個使用者的可用空間不同
- 5.允許使用者在ftp server上随意切換目錄
- 6.允許使用者檢視目前目錄下檔案
- 7.允許上傳和下載下傳檔案,保證檔案一緻性(md5)
- 8.檔案傳輸過程中顯示進度條
- 9.附加功能:支援檔案的斷點續傳
## 本項目思路
- 1 對于此項目,最初的想法是寫出上傳,和下載下傳檔案的程式,包括用戶端和服務端。
-  2 在此基礎上擴充程式,包括提出開始程式到bin裡面,配置檔案在config裡面
-  3 然後把上傳檔案和下載下傳檔案的程式進行斷點續傳的程式重構
-   4 在此基礎上,對檔案進行加密
-   5 增加功能,包括設定進度條,增加檢視功能,增加目錄功能,删除檔案功能,切換目錄功能等
-   6 然後再設定磁盤配置設定功能,完善内容
-   7 然後添加使用者登陸,包括對使用者的密碼加密等功能
-   8 寫完後檢查程式


##### 備注(程式結構)
> 目前還不會把程式樹放在README.md裡面,是以做出程式結構的txt版本和圖檔版本,放在檔案外面友善檢視

## 對幾個執行個體檔案的說明
### 幾個執行個體檔案全是為了上傳和下載下傳使用,自己随便找的素材

## 不足及其改進的方面
### 每次程式從使用者登陸到使用隻能完成一次功能,不能重複使用

## 程式結構

│  FTP_homework
│  __init__.py
│  
├─client                # 用戶端程式入口
│  │  __init__.py
│  ├─bin                # 可執行程式入口目錄
│  │      run.py
│  │      __init__.py
│  ├─config             # 配置檔案目錄
│  │  │  settings.py    # 配置檔案
│  │  │  __init__.py       
│  ├─core               # 主要邏輯程式目錄
│  │  │  ftp_client.py  # client端主程式子產品
│  │  │  __init__.py       
│  ├─download           # 下載下傳内容子產品
│  │      a.jpg 
│  │      a.txt
│  │      c.mp4  
│  └─upload             # 上傳内容子產品
│          a.txt
│          aa.avi
└─server                 # 服務端程式入口
    ├─bin
    │      run.py        # 可執行程式入口目錄
    │      __init__.py 
    ├─config             # 配置檔案目錄
    │  │  accounts.ini   # 賬号密碼配置檔案
    │  │  settings.py    # 配置檔案
    │  │  __init__.py        
    ├─core               # 主要邏輯程式目錄
    │  │  ftp_server.py  # server端主程式子產品
    │  │  main.py        # 主程式子產品
    │  │  user_handle.py # 使用者注冊登入子產品  
    └─home               # 家目錄
        │  __init__.py
        ├─curry          # curry使用者的家目錄
        │  │  aa.avi
        │  └─test
        └─james           # james使用者的家目錄
            │  a.jpg
            │  aa.avi
            │  c.mp4
            └─test1
      

七,程式結構圖

開發一個支援多使用者線上的FTP程式

 八,程式代碼

1,server

1.1 bin

run.py

# _*_ coding: utf-8 _*_
import os
import sys


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)


from core import ftp_server
from core import main
from config import settings

if __name__ == '__main__':
    a = main.Manager()
    a.interactive()
      

1.2config

settings.py

# _*_ coding: utf-8 _*_ 
import os
import sys
import socket

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

ACCOUNTS_FILE = os.path.join(BASE_DIR,'config','accounts.ini')

address_family = socket.AF_INET
socket_type = socket.SOCK_STREAM

BIND_HOST = '127.0.0.1'
BIND_PORT = 9999
ip_port = (BIND_HOST,BIND_PORT)
coding = 'utf-8'
listen_count = 5
max_recv_bytes = 8192
allow_reuser_address = False
      

1.3core

ftp_server.py

# _*_ coding: utf-8 _*_
import socket
import struct
import json
import os
import pickle
import subprocess
import hashlib

from config import settings
from core.user_handle import UserHandle

class FTPServer():

    def __init__(self,server_address,bind_and_listen = True):
        self.server_address = server_address
        self.socket = socket.socket(settings.address_family,settings.socket_type)
        if bind_and_listen:
            try:
                self.server_bind()
                self.server_listen()
            except Exception:
                self.server_close()

    def server_bind(self):
        allow_reuse_address = False
        if allow_reuse_address:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)

    def server_listen(self):
        self.socket.listen(settings.listen_count)

    def server_close(self):
        self.socket.close()

    def server_accept(self):
        return self.socket.accept()

    def conn_close(self, conn):
        conn.close()

    def getfile_md5(self):
        '''擷取檔案的md5'''
        return hashlib.md5(self.readfile()).hexdigest()

    def readfile(self):
        '''讀取檔案,得到檔案内容的bytes類型'''
        with open(self.file_path,'rb') as f:
            filedata = f.read()
        return filedata

    def send_filedata(self,exist_file_size=0):
        """下載下傳時,将檔案打開,send(data)"""
        with open(self.file_path, 'rb') as f:
            f.seek(exist_file_size)
            while True:
                data = f.read(1024)
                if data:
                    self.conn.send(data)
                else:
                    break

    def get(self, cmds):
        '''
       下載下傳,首先檢視檔案是否存在,然後上傳檔案的報頭大小,上傳檔案,以讀的方式發開檔案
       找到下載下傳的檔案
    發送 header_size
    發送 header_bytes file_size
    讀檔案 rb 發送 send(line)
    若檔案不存在,發送0 client提示:檔案不存在
       :param cmds:
       :return:
               '''
        if len(cmds) > 1:
            filename = cmds[1]
            self.file_path = os.path.join(os.getcwd(), filename)
            if os.path.isfile(self.file_path):
                file_size = os.path.getsize(self.file_path)
                obj = self.conn.recv(4)
                exist_file_size = struct.unpack('i', obj)[0]
                header = {
                    'filename': filename,
                    'filemd5': self.getfile_md5(),
                    'file_size': file_size
                }
                header_bytes = pickle.dumps(header)
                self.conn.send(struct.pack('i', len(header_bytes)))
                self.conn.send(header_bytes)
                if exist_file_size:  # 表示之前被下載下傳過 一部分
                    if exist_file_size != file_size:
                        self.send_filedata(exist_file_size)
                    else:
                        print('\033[31;1mbreakpoint and file size are the same\033[0m')
                else:  # 檔案第一次下載下傳
                    self.send_filedata()
            else:
                print('\033[31;1merror\033[0m')
                self.conn.send(struct.pack('i', 0))

        else:
            print("\033[31;1muser does not enter file name\033[0m")

    def recursion_file(self, dir):
        """遞歸查詢使用者目錄下的所有檔案,算出檔案的大小"""
        res = os.listdir(dir)
        for i in res:
            path = os.path.join(dir,i)
            if os.path.isdir(path):
                self.recursion_file(path)
            elif os.path.isfile(path):
                self.home_bytes_size += os.path.getsize(path)

    def current_home_size(self):
        """得到目前使用者目錄的大小,位元組/M"""
        self.home_bytes_size =0
        self.recursion_file(self.homedir_path)
        home_m_size = round(self.home_bytes_size / 1024 / 1024, 1)

    def put(self,cmds):
        """從client上傳檔案到server目前工作目錄下
        """
        if len(cmds) >1:
            obj = self.conn.recv(4)
            state_size = struct.unpack('i', obj)[0]
            if state_size ==0:
                print("\033[31;1mfile does not exist!\033[0m")
            else:
                # 算出了home下已被占用的大小self.home_bytes_size
                self.current_home_size()
                header_bytes = self.conn.recv(struct.unpack('i', self.conn.recv(4))[0])
                header_dic = pickle.loads(header_bytes)
                filename = header_dic.get('filename')
                file_size = header_dic.get('file_size')
                file_md5 = header_dic.get('file_md5')
                self.file_path = os.path.join(os.getcwd(),filename)
                if os.path.exists(self.file_path):
                    self.conn.send(struct.pack('i',1))
                    has_size = os.path.getsize(self.file_path)
                    if has_size == file_size:
                        print("\033[31;1mfile already does exist!\033[0m")
                        self.conn.send(struct.pack('i', 0))
                    else:
                        print('\033[31;1mLast file not finished,this time continue\033[0m')
                        self.conn.send(struct.pack('i', 1))
                        if self.home_bytes_size + int(file_size-has_size)>self.quota_bytes:
                            print('\033[31;1mSorry exceeding user quotas\033[0m')
                            self.conn.send(struct.pack('i', 0))
                        else:
                            self.conn.send(struct.pack('i', 1))
                            self.conn.send(struct.pack('i', has_size))
                            with open(self.file_path, 'ab') as f:
                                f.seek(has_size)
                                self.write_file(f, has_size, file_size)
                            self.verification_filemd5(file_md5)
                else:
                    self.conn.send(struct.pack('i', 0))
                    print('\033[31;1mSorry file does not exist now first put\033[0m')
                    if self.home_bytes_size + int(file_size) > self.quota_bytes:
                        print('\033[31;1mSorry exceeding user quotas\033[0m')
                        self.conn.send(struct.pack('i', 0))
                    else:
                        self.conn.send(struct.pack('i', 1))
                        with open(self.file_path,'wb') as f:
                            recv_size = 0
                            self.write_file(f, recv_size, file_size)
                        self.verification_filemd5(file_md5)

        else:
            print("\033[31;1muser does not enter file name\033[0m")
    def write_file(self,f,recv_size,file_size):
        '''上傳檔案時,将檔案内容寫入到檔案中'''
        while recv_size < file_size:
            res = self.conn.recv(settings.max_recv_bytes)
            f.write(res)
            recv_size += len(res)
            self.conn.send(struct.pack('i', recv_size))  # 為了進度條的顯示

    def verification_filemd5(self,filemd5):
        # 判斷檔案内容的md5
        if self.getfile_md5() == filemd5:
            print('\033[31;1mCongratulations download success\033[0m')
            self.conn.send(struct.pack('i', 1))
        else:
            print('\033[31;1mSorry download failed\033[0m')
            self.conn.send(struct.pack('i', 0))

    def ls(self,cmds):
        '''檢視目前工作目錄下,先傳回檔案清單的大小,在傳回查詢的結果'''
        print("\033[34;1mview current working directory\033[0m")
        subpro_obj = subprocess.Popen('dir',shell=True,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
        stdout = subpro_obj.stdout.read()
        stderr = subpro_obj.stderr.read()
        self.conn.send(struct.pack('i',len(stdout + stderr)))
        self.conn.send(stdout)
        self.conn.send(stderr)

    def mkdir(self,cmds):
        '''增加目錄
        在目前目錄下,增加目錄
        1.檢視目錄名是否已經存在
        2.增加目錄成功,傳回 1
        2.增加目錄失敗,傳回 0'''
        print("\033[34;1madd working directory\033[0m")
        if len(cmds) >1:
            mkdir_path = os.path.join(os.getcwd(),cmds[1])
            if not os.path.exists(mkdir_path):
                os.mkdir(mkdir_path)
                print('\033[31;1mCongratulations add directory success\033[0m')
                self.conn.send(struct.pack('i',1))
            else:
                print("\033[31;1muser directory already does exist\033[0m")
                self.conn.send(struct.pack('i',0))
        else:
            print("\033[31;1muser does not enter file name\033[0m")

    def cd(self,cmds):
        '''切換目錄
        1.檢視是否是目錄名
        2.拿到目前目錄,拿到目标目錄,
        3.判斷homedir是否在目标目錄内,防止使用者越過自己的home目錄 eg: ../../....
        4.切換成功,傳回 1
        5.切換失敗,傳回 0'''
        print("\033[34;1mSwitch working directory\033[0m")
        if len(cmds) > 1:
            dir_path = os.path.join(os.getcwd(),cmds[1])
            if os.path.isdir(dir_path):
                #os.getcwd 擷取目前工作目錄
                previous_path = os.getcwd()
                #os.chdir改變目前腳本目錄
                os.chdir(dir_path)
                target_dir = os.getcwd()
                if self.homedir_path in target_dir:
                    print('\033[31;1mCongratulations switch directory success\033[0m')
                    self.conn.send(struct.pack('i', 1))
                else:
                    print('\033[31;1mSorry switch directory failed\033[0m')
                    # 切換失敗後,傳回到之前的目錄下
                    os.chdir(previous_path)
                    self.conn.send(struct.pack('i', 0))
            else:
                print('\033[31;1mSorry switch directory failed,the directory is not current directory\033[0m')
                self.conn.send(struct.pack('i', 0))
        else:
            print("\033[31;1muser does not enter file name\033[0m")

    def remove(self,cmds):
        """删除指定的檔案,或者空檔案夾
               1.删除成功,傳回 1
               2.删除失敗,傳回 0
               """
        print("\033[34;1mRemove working directory\033[0m")
        if len(cmds) > 1:
            file_name = cmds[1]
            file_path = os.path.join(os.getcwd(),file_name)
            if os.path.isfile(file_path):
                os.remove(file_path)
                self.conn.send(struct.pack('i', 1))
            elif os.path.isdir(file_path):  # 删除空目錄
                if not len(os.listdir(file_path)):
                    os.removedirs(file_path)
                    print('\033[31;1mCongratulations remove success\033[0m')
                    self.conn.send(struct.pack('i', 1))
                else:
                    print('\033[31;1mSorry remove directory failed\033[0m')
                    self.conn.send(struct.pack('i', 0))
            else:
                print('\033[31;1mSorry remove directory failed\033[0m')
                self.conn.send(struct.pack('i', 0))
        else:
            print("\033[31;1muser does not enter file name\033[0m")

    def get_recv(self):
        '''從client端接收發來的資料'''
        return pickle.loads(self.conn.recv(settings.max_recv_bytes ))

    def handle_data(self):
        '''處理接收到的資料,主要是将密碼轉化為md5的形式'''
        user_dic = self.get_recv()
        username = user_dic['username']
        password = user_dic['password']
        md5_obj = hashlib.md5()
        md5_obj.update(password)
        check_password = md5_obj.hexdigest()

    def auth(self):
        '''
        處理使用者的認證請求
        1,根據username讀取accounts.ini檔案,然後檢視使用者是否存在
        2,将程式運作的目錄從bin.user_auth修改到使用者home/username友善之後查詢
        3,把用戶端傳回使用者的詳細資訊
        :return:
        '''
        while True:
            user_dic = self.get_recv()
            username = user_dic['username']
            password = user_dic['password']
            md5_obj = hashlib.md5(password.encode('utf-8'))
            check_password = md5_obj.hexdigest()
            user_handle  = UserHandle(username)
            # 判斷使用者是否存在 傳回清單,
            user_data = user_handle.judge_user()
            if user_data:
                if user_data[0][1] ==check_password:
                    self.conn.send(struct.pack('i',1))  # 登入成功傳回 1
                    self.homedir_path = os.path.join(settings.BASE_DIR,'home',username)
                    # 将程式運作的目錄名修改到 使用者home目錄下
                    os.chdir(self.homedir_path)
                    # 将使用者配額的大小從M 改到位元組
                    self.quota_bytes = int(user_data[2][1])*1024*1024
                    user_info_dic = {
                        'username':username,
                        'homedir':user_data[1][1],
                        'quota':user_data[2][1]
                    }
                    # 使用者的詳細資訊發送到用戶端
                    self.conn.send(pickle.dumps(user_info_dic))
                    return True
                else:
                    self.conn.send(struct.pack('i', 0))  # 登入失敗傳回 0
            else:
                self.conn.send(struct.pack('i', 0))  # 登入失敗傳回 0

    def server_link(self):
        print("\033[31;1mwaiting client .....\033[0m")
        while True:  # 連結循環
            self.conn,self.client_addr = self.server_accept()
            while True:  # 通信循環
                try:
                    self.server_handle()
                except Exception:
                    break
            self.conn_close(self.conn)
    def server_handle(self):
        '''處理與使用者的互動指令'''
        if self.auth():
            print("\033[32;1m-------user authentication successfully-------\033[0m")
            res = self.conn.recv(settings.max_recv_bytes)
            # 解析指令,提取相應的參數
            cmds = res.decode(settings.coding).split()
            if hasattr(self, cmds[0]):
                func = getattr(self, cmds[0])
                func(cmds)
      

main.py

# _*_ coding: utf-8 _*_ 
from core.user_handle import UserHandle
from core.ftp_server import FTPServer
from config import settings


class Manager():
    '''
    主程式,包括啟動server,建立使用者,退出
    :return:
    '''
    def start_ftp(self):
        '''啟動server端'''
        server = FTPServer(settings.ip_port)
        server.server_link()
        server.close()

    def create_user(self):
        '''建立使用者,執行建立使用者的類'''
        username =  input("\033[32;1mplease input your username>>>\033[0m").strip()
        UserHandle(username).add_user()

    def logout(self):
        '''
        退出登陸
        :return:
        '''
        print("\033[32;1m-------Looking forward to your next login-------\033[0m")
        exit()
    def interactive(self):
        '''互動函數'''
        msg = '''\033[32;1m
                       1   啟動ftp服務端
                       2   建立使用者
                       3   退出
               \033[0m'''
        menu_dic = {
            "1": 'start_ftp',
            "2": 'create_user',
            "3": 'logout',
        }
        exit_flag = False
        while not exit_flag:
            print(msg)
            user_choice = input("Please input a command>>>").strip()
            if user_choice in menu_dic:
                getattr(self,menu_dic[user_choice])()
            else:
                print("\033[31;1myou choice doesn't exist\033[0m")
      

user_handle.py

# _*_ coding: utf-8 _*_ 
import configparser
import hashlib
import os

from config import settings

class UserHandle():
    '''
    建立使用者名稱,密碼
    如果使用者存在,則傳回,如果使用者不存在,則注冊成功
    '''
    def __init__(self,username):
        self.username = username
        self.config = configparser.ConfigParser()
        self.config.read(settings.ACCOUNTS_FILE)

    @property
    def password(self):
        '''生成使用者的預設密碼 '''
        password_inp = input("\033[32;1mplease input your password>>>\033[0m").strip()
        md5_obj = hashlib.md5()
        md5_obj.update(password_inp.encode())
        md5_password = md5_obj.hexdigest()
        return md5_password

    @property
    def disk_quota(self):
        '''生成每個使用者的磁盤配額'''
        quota = input('\033[32;1mplease input Disk quotas>>>:\033[0m').strip()
        if quota.isdigit():
            return quota
        else:
            exit('\033[31;1mdisk quotas must be integer\033[0m')

    def add_user(self):
        """建立使用者,存到accounts.ini"""
        if not self.config.has_section(self.username):
            print('\033[31;1mcreating username is :%s \033[0m' %self.username)
            self.config.add_section(self.username)
            self.config.set(self.username, 'password', self.password)
            self.config.set(self.username, 'homedir', 'home/' + self.username)
            self.config.set(self.username, 'quota', self.disk_quota)
            with open(settings.ACCOUNTS_FILE, 'w') as f:
                self.config.write(f)
            os.mkdir(os.path.join(settings.BASE_DIR, 'home', self.username))  # 建立使用者的home檔案夾
            print('\033[1;32msuccessfully create userdata\033[0m')
        else:
            print('\033[1;31musername already existing\033[0m')

    def judge_user(self):
        """判斷使用者是否存在"""
        if self.config.has_section(self.username):
            return self.config.items(self.username)
      

2,client

2.1bin

# _*_ coding: utf-8 _*_
import os
import sys


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)


from core import ftp_client
from config import settings
if __name__ == '__main__':
    run = ftp_client.FTPClient(settings.ip_port)
    run.execute()
      

2.2config

# _*_ coding: utf-8 _*_
import os
import sys
import socket

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
# 下載下傳的檔案存放路徑
down_filepath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'download')
# 上傳的檔案存放路徑
upload_filepath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'upload')
#綁定的IP位址
BIND_HOST = '127.0.0.1'
#綁定的端口号
BIND_PORT = 9999
ip_port = (BIND_HOST,BIND_PORT)
address_family = socket.AF_INET
socket_type = socket.SOCK_STREAM

coding = 'utf-8'
listen_count = 5
max_recv_bytes = 8192
allow_reuser_address = False
      

2.3core

ftp_client.py

# _*_ coding: utf-8 _*_ 
import socket
import struct
import json
import os
import sys
import pickle
import hashlib

from config import settings

class FTPClient:

    def __init__(self,server_address,connect = True):
        self.server_address = server_address
        self.socket = socket.socket(settings.address_family,settings.socket_type)
        if connect:
            try:
                self.client_connect()
            except Exception:
                self.client_close()

    def client_connect(self):
        try:
            self.socket.connect(self.server_address)
        except Exception as e:
            print("\033[31;1merror:%s\033[0m"%e)
            exit("\033[31;1m\nThe server is not activated \033[0m")

    def client_close(self):
        self.socket.close()

    def readfile(self):
        '''讀取檔案'''
        with open(self.file_path,'rb') as f:
            filedata = f.read()
        return filedata

    def appendfile_content(self,file_path,temp_file_size,file_size):
        '''追加檔案内容'''
        with open(file_path,'ab') as f:
            f.seek(temp_file_size)
            get_size = temp_file_size
            while get_size < file_size:
                res = self.socket.recv(settings.max_recv_bytes)
                f.write(res)
                get_size += len(res)
                self.progress_bar(1,get_size,file_size)  #1表示下載下傳

    def getfile_md5(self):
        '''對檔案内容進行加密,也就是保持檔案的一緻性'''
        md5 = hashlib.md5(self.readfile())
        print("md5是:\n",md5.hexdigest())
        return md5.hexdigest()

    def progress_bar(self,num,get_size,file_size):
        float_rate = float(get_size) / float(file_size)
        rate_num = round(float_rate * 100,2)
        if num ==1: #1表示下載下傳
            sys.stdout.write('\033[31;1m\rfinish downloaded perentage:{0}%\033[0m'.format(rate_num))
        elif num ==2:  #2表示上傳
            sys.stdout.write('\033[31;1m\rfinish uploaded perentage:{0}%\033[0m'.format(rate_num))
        sys.stdout.flush()

    def recv_file_header(self,header_size):
        """接收檔案的header, filename file_size file_md5"""
        header_types = self.socket.recv(header_size)
        header_dic = pickle.loads(header_types)
        print(header_dic, type(header_dic))
        total_size = header_dic['file_size']
        filename = header_dic['filename']
        filemd5 = header_dic['filemd5']
        return (filename,total_size,filemd5)

    def verification_filemd5(self,filemd5):
        # 判斷下載下傳下來的檔案MD5值和server傳過來的MD5值是否一緻
        if self.getfile_md5() == filemd5:
            print('\033[31;1mCongratulations download success\033[0m')
        else:
            print('\033[31;1mSorry download failed,download again support breakpoint continuation\033[0m')
    def write_file(self,f,get_size,file_size):
        '''下載下傳檔案,将内容寫入檔案中'''
        while get_size < file_size:
            res = self.socket.recv(settings.max_recv_bytes)
            f.write(res)
            get_size += len(res)
            self.progress_bar(1,get_size,file_size)  #1表示下載下傳

    def get(self,cmds):
        """從server下載下傳檔案到client
        """
        if len(cmds) >1:
            filename = cmds[1]
            self.file_path = os.path.join(settings.down_filepath, filename)
            if os.path.isfile(self.file_path):  #如果檔案存在,支援斷電續傳
                temp_file_size = os.path.getsize(self.file_path)
                self.socket.send(struct.pack('i',temp_file_size))
                header_size = struct.unpack('i',self.socket.recv(4))[0]
                if header_size:
                    filename,file_size,filemd5 = self.recv_file_header(header_size)
                    if temp_file_size == file_size:
                        print('\033[34;1mFile already does exist\033[0m')
                    else:
                        print('\033[34;1mFile now is breakpoint continuation\033[0m')
                        self.appendfile_content(self.file_path,temp_file_size)
                        self.verification_filemd5(filemd5)
                else:
                    print("\033[34;1mFile was downloaded before,but now server's file is not exist\033[0m")
            else:#如果檔案不存在,則是直接下載下傳
                self.socket.send(struct.pack('i',0))
                obj = self.socket.recv(1024)
                header_size = struct.unpack('i', obj)[0]
                if header_size==0:
                    print("\033[31;1mfile does not exist!\033[0m")
                else:
                    filename, file_size, filemd5 = self.recv_file_header(header_size)
                    download_filepath = os.path.join(settings.down_filepath, filename)
                    with open(download_filepath, 'wb') as f:
                        get_size = 0
                        self.write_file(f, get_size, file_size)
                    self.verification_filemd5(filemd5)
        else:
            print("\033[31;1muser does not enter file name\033[0m")

    def ls(self,cmds):
        '''檢視目前工作目錄,檔案清單'''
        print("\033[34;1mview current working directory\033[0m")
        obj = self.socket.recv(4)
        dir_size = struct.unpack('i',obj)[0]
        recv_size = 0
        recv_bytes = b''
        while recv_size <dir_size:
            temp_bytes = self.socket.recv(settings.max_recv_bytes)
            recv_bytes +=temp_bytes
            recv_size += len(temp_bytes)
        print(recv_bytes.decode('gbk'))

    def mkdir(self,cmds):
        '''增加目錄
        1,server傳回1 增加成功
        2,server傳回2 增加失敗'''
        print("\033[34;1madd working directory\033[0m")
        obj = self.socket.recv(4)
        res = struct.unpack('i',obj)[0]
        if res:
            print('\033[31;1mCongratulations add directory success\033[0m')
        else:
            print('\033[31;1mSorry add directory failed\033[0m')

    def cd(self,cmds):
        '''切換目錄'''
        print("\033[34;1mSwitch working directory\033[0m")
        if len(cmds) >1:
            obj = self.socket.recv(4)
            res = struct.unpack('i', obj)[0]
            if res:
                print('\033[31;1mCongratulations switch directory success\033[0m')
            else:
                print('\033[31;1mSorry switch directory failed\033[0m')
        else:
            print("\033[31;1muser does not enter file name\033[0m")

    def remove(self,cmds):
        '''表示删除檔案或空檔案夾'''
        print("\033[34;1mRemove working directory\033[0m")
        obj = self.socket.recv(4)
        res = struct.unpack('i', obj)[0]
        if res:
            print('\033[31;1mCongratulations remove success\033[0m')
        else:
            print('\033[31;1mSorry remove directory failed\033[0m')

    def open_sendfile(self,file_size,recv_size =0):
        '''打開要上傳的檔案(由于本程式上傳檔案的原理是先讀取本地檔案,再寫到上傳位址的檔案)'''

        with open(self.file_path, 'rb') as f:
            # send_bytes = b''
            # send_size = 0
            f.seek(recv_size)
            while True:
                data = f.read(1024)
                if data:
                    self.socket.send(data)
                    obj = self.socket.recv(4)
                    recv_size = struct.unpack('i', obj)[0]
                    self.progress_bar(2, recv_size, file_size)
                else:
                    break
        success_state = struct.unpack('i', self.socket.recv(4))[0]
        if success_state:
            print('\033[31;1mCongratulations upload success\033[0m')
        else:
            print('\033[31;1mSorry upload directory failed\033[0m')

    def put_situation(self,file_size,condition=0):
        '''上傳的時候有兩種情況,檔案已經存在,檔案不存在'''
        quota_state= struct.unpack('i', self.socket.recv(4))[0]
        if quota_state:
            if condition:
                obj = self.socket.recv(4)
                recv_size = struct.unpack('i', obj)[0]
                self.open_sendfile(file_size,recv_size)
            else:
                self.open_sendfile(file_size)
        else:
            print('\033[31;1mSorry exceeding user quotas\033[0m')

    def put(self,cmds):
        """往server端登入的使用者目錄下上傳檔案
        """
        if len(cmds) > 1:
            filename = cmds[1]
            self.file_path = os.path.join(settings.upload_filepath, filename)
            if os.path.isfile(self.file_path):  # 如果檔案存在,支援斷電續傳
                self.socket.send(struct.pack('i', 1))
                file_size = os.path.getsize(self.file_path)
                header_dic = {
                    'filename': os.path.basename(filename),
                    'file_md5': self.getfile_md5(),
                    'file_size': file_size
                }
                header_bytes = pickle.dumps(header_dic)
                self.socket.send(struct.pack('i', len(header_bytes)))
                self.socket.send(header_bytes)
                state = struct.unpack('i', self.socket.recv(4))[0]
                if state:  #已經存在
                    has_state = struct.unpack('i', self.socket.recv(4))[0]
                    if has_state:
                        self.put_situation(file_size, 1)
                    else:  # 存在的大小 和檔案大小一緻 不必再傳
                        print("\033[31;1mfile already does exist!\033[0m")
                else:  # 第一次傳
                        self.put_situation(file_size)
            else:  # 檔案不存在
                print("\033[31;1mfile does not exist!\033[0m")
                self.socket.send(struct.pack('i', 0))
        else:
            print("\033[31;1muser does not enter file name\033[0m")

    def get_recv(self):
        '''從client端接受發來的資料'''
        return pickle.loads(self.socket.recv(settings.max_recv_bytes))

    def login(self):
        '''
        登陸函數,當登陸失敗超過三次,則退出
        使用者密碼發送到server短
        接受server端傳回的資訊,如果成功傳回1,失敗傳回0
        :return: 如果使用者賬号密碼正确,則傳回使用者資料的字典
        '''
        retry_count = 0
        while retry_count <3:
            username = input('\033[34;1mplease input Username:\033[0m').strip()
            if not username:
                continue
            password = input('\033[34;1mplease input Password:\033[0m').strip()
            user_dic = {
                'username':username,
                'password':password
            }
            #将使用者資訊發送到用戶端,然後接受用戶端的資料
            data = pickle.dumps(user_dic)
            self.socket.send(pickle.dumps(user_dic))
            #為了防止出現黏包問題,是以先解壓報頭,讀取報頭,再讀資料
            obj = self.socket.recv(4)
            res = struct.unpack('i',obj)[0]
            #此處,如果傳回的是代碼4001,則成功 4002則失敗
            if res:
                print("\033[32;1m-----------------welcome to ftp client-------------------\033[0m")
                user_info_dic = self.get_recv()
                recv_username = user_info_dic['username']
                return True
            else:
                print("\033[31;1mAccount or Passwordoes not correct!\033[0m")
        retry_count +=1

    def execute(self):
        '''
        執行,或者實施
        :return:
        '''
        if self.login():
            while True:
                try:
                    self.help_info()
                    inp = input("Please input a command>>>").strip()
                    if not inp:
                        continue
                    self.socket.send(inp.encode(settings.coding))
                    cmds = inp.split()
                    if hasattr(self, cmds[0]):
                        func = getattr(self, cmds[0])
                        func(cmds)
                        break
                    else:
                        print('\033[31;1mNo such command ,please try again\033[0m')
                except Exception as e:  # server關閉了
                    print('\033[31;1m%s\033[0m'%e)
                    break

    def help_info(self):
        print ('''\033[34;1m
              get + (檔案名)    表示下載下傳檔案
              put + (檔案名)    表示上傳檔案
              ls                 表示查詢目前目錄下的檔案清單(隻能通路自己的檔案清單) 
              mkdir + (檔案名)  表示建立檔案夾  
              cd + (檔案名)     表示切換目錄(隻能在自己的檔案清單中切換)
              remove + (檔案名) 表示删除檔案或空檔案夾
        \033[0m''')
      

不經一番徹骨寒 怎得梅花撲鼻香

繼續閱讀