基於python的ftp(含資料庫、含多執行緒、含socketserver)

專注的阿熊發表於2021-01-12

直接上程式碼:

伺服器端:

import  pymysqlimport socketserverimport timeimport os

xieyi='''

    +----------------------+

        1. 想伺服器端上傳檔案

        2. 從伺服器端下載檔案

    +----------------------+

    '''

login='''

    +----------------------+

    +         身份驗證         +

    +     請輸入使用者名稱和密碼:   +   

    +----------------------+

    '''

# 例項化 class MyTCPhandler(socketserver.BaseRequestHandler):

    def handle(self):

        try:

            conn = pymysql.connect(

                host='localhost',

                user='root',

                password='cl19970312',

                db='ftp',

                charset='utf8',

            )

        except pymysql.Error as e:

            print(" 資料庫連線失敗 ", e)

            exit()

        finally:

            root_path = 'E:\ 堡壘機開發 \server//'

            print(" 資料庫連線成功 ")

            self.cur = conn.cursor()

            while True:

                try:

                    self.login_yanzheng = False

                    self.data=self.request.recv(1024)

                    print('{}:{}wrote:'.format(self.client_address[0],self.client_address[1]))

                    print("data:",self.data.decode('utf-8'))

                    if check_connect(self.data,self.cur):

                        print(" 登陸成功 ")

                        id=check_connect(self.data,self.cur)

                        self.login_yanzheng=True

                        self.request.send(" 登陸成功 ".encode('utf-8'))

                        if self.request.recv(1024).decode('utf-8')=='1':

                            print(" 準備接收檔案 ")

                            self.request.send("OK".encode('utf-8'))

                            data=self.request.recv(10000000)

                            save_data(data,id,self.cur)

                            self.request.close()

                            conn.commit()

                        else:

                            print(" 準備向客戶端傳送檔案 ")

                            data=query(id,self.cur)

                            if  not data:

                                self.request.send(" 未找到您的上傳記錄 ".encode('utf-8'))

                                print(" {} 斷開連線 ".format(self.client_address[0]))

                                self.request.close()

                            else:

                                self.request.send(data.encode('utf-8'))

                                request=self.request.recv(1024).decode('utf-8')

                                if isfile(root_path+request+'.jpg'):

                                    data=readfile(root_path+request+'.jpg')

                                    self.request.send(data)

                                else:

                                    self.request.send('')

                    else:

                        print(" 登陸失敗 ")

                        self.login_yanzheng=False

                        self.request.send(" 登陸失敗,使用者名稱不存在 ".encode('utf-8'))

                except ConnectionError as e:

                    print(e)

                    break

                except:

                    breakdef check_connect(data,cur):

    data=data.decode('utf-8').split()

    id,password=data[0],data[1]

    sql='select * from user where id={};'.format(id)

    cur.execute(sql)

    results=cur.fetchall()

    if results[0][0]==id and results[0][1]==password:

        return id

    else:

        return None

def isfile(filename):

    result=os.path.exists(filename)

    return resultdef readfile(filename):

    with open(filename,'rb') as f:

        data=f.read()

    return datadef save_data(data,id,cur):

    today_now = time.strftime('%Y%m%d%H%M%S')

    filename=id+today_now+'.jpg'

    root_path='E:\ 堡壘機開發 \server//'

    #os.makedirs(root_path)

    with open(root_path+filename,'wb') as f:

        f.write(data)

    sql='insert into file values("{}","{}");'.format(id,filename.split('.')[0])

    print(sql)

    cur.execute(sql)

    print(" 檔案上傳成功,共 {} 位元組 ".format(len(data)))

def query(id,cur):

    try:

        sql='select filename from file where id="{}";'.format(id)

        cur.execute(sql)

        results=cur.fetchall()

        data=''

        for result in results:

            data+=str(result)+','

        return data

    except pymysql.Error as e:

        print(e)

        return None

if __name__=='__main__':

    HOST,PORT='localhost',8080

    server=socketserver.ThreadingTCPServer((HOST,PORT),MyTCPhandler)

    server.serve_forever()

客戶端:

from socket import *import timeimport os

client=socket()

client.connect(('localhost',8080))

xieyi='''

    +----------------------+

        1. 想伺服器端上傳檔案

        2. 從伺服器端下載檔案

    +----------------------+

    '''

login='''

    +----------------------+

    +         身份驗證         +

    +     請輸入使用者名稱和密碼:   +   

    +----------------------+

    '''def handle_data():

    is_quit = False

    while True:

        if is_quit:

            break

        send_mas = input(xieyi).strip()

        if send_mas in ['1','2']:

            if send_mas=="1":

                client.send(send_mas.encode('utf-8'))

                if client.recv(1024).decode('utf-8')=='OK':

                    while True:

                        filename=input(" 請輸入檔名: ").strip()

                        root_path ='E:\ 堡壘機開發 \client//'

                        print(root_path+filename)

                        if isfile(root_path+filename):

                            print(" 檔案存在 ")

                            client.send(readfile(root_path+filename))

                            print(" 檔案傳送成功,共 {} 位元組 ".format(len(readfile(root_path+filename))))

                            is_quit=True

                            exit()

                            break

                        else:

                            print(" 檔案不存在 ")

                            continue

                else:

                    break

            else:

                client.send(send_mas.encode('utf-8'))

                data=client.recv(1024)

                if data==' 未找到您的上傳記錄 ':

                    print(" 未找到上傳記錄 ")

                    client.close()

                else:

                    print(" 一共有以下檔案可以下載 ")

                    print(data.decode('utf-8'))

                    data=input(" 請輸入您選擇的檔案 >>").strip()

                    client.send(data.encode('utf-8'))

                    data=client.recv(1000000)

                    if data:

                        save_file(data)

                        break

                    else:

                        print(" 檔案被刪除 ")

        else:

            print(" 輸入錯誤,請重新輸入 ")def isfile(filename):

    result=os.path.exists(filename)

    return res跟單網 readfile(filename):

    with open(filename,'rb') as f:

        data=f.read()

    return datadef main():

    print(login)

    send_mas = input(">>").strip()

    client.send(send_mas.encode('utf-8'))

    recv_data = client.recv(1024)

    if recv_data.decode('utf-8') == ' 登陸成功 ':

        print(" 服務端允許獲得連線 ")

        handle_data()

    else:

        print(" 伺服器端不允許獲得連線 ")def save_file(data):

    today_now = time.strftime('%Y%m%d%H%M%S')

    filename =today_now + '.jpg'

    root_path = 'E:\ 堡壘機開發 \client//'

    # os.makedirs(root_path)

    with open(root_path + filename, 'wb') as f:

        f.write(data)

    print(" 檔案儲存成功 ! {} 位元組 ".format(len(data)))

if __name__=='__main__':

    main()

readme:

ftp:

身份驗證:

     成功:

         上傳檔案

             儲存檔案(server

         下載檔案

             儲存檔案(client

     失敗:

         退出

mysql:

     開啟命令列輸入

        mysql -u root -p→

        →password→

        show databases;

        create database ftp;

        use ftp;

        create table user(id varchar(40) primary key,

                          password varchar(40));

        insert into user value('000001','123456'),('000002','123456'),('000003','654321');


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2749251/,如需轉載,請註明出處,否則將追究法律責任。

相關文章