码迷,mamicode.com
首页 > 其他好文 > 详细

FTP之进度条,cd切换,创建文件夹及校验思路

时间:2019-06-06 23:07:03      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:stat   inpu   targe   dirname   settings   add   show   try   hand   

\r 回车,回到当前行的行首,不会换到下一行,如果接着输出的话,本行以前的内容会被逐一覆盖

技术图片
import optparse
import socket
import configparser
import json
import os,sys

STATUS_CODE  = {
    250 : "Invalid cmd format, e.g: {‘action‘:‘get‘,‘filename‘:‘test.py‘,‘size‘:344}",
    251 : "Invalid cmd ",
    252 : "Invalid auth data",
    253 : "Wrong username or password",
    254 : "Passed authentication",
    255 : "Filename doesn‘t provided",
    256 : "File doesn‘t exist on server",
    257 : "ready to send file",
    258 : "md5 verification",

    800 : "the file exist,but not enough ,is continue? ",
    801 : "the file exist !",
    802 : " ready to receive datas",

    900 : "md5 valdate success"

}

class ClientHandler():

    def __init__(self):
        self.op=optparse.OptionParser()

        self.op.add_option("-s","--server",dest="server")
        self.op.add_option("-P","--port",dest="port")
        self.op.add_option("-u","--username",dest="username")
        self.op.add_option("-p","--password",dest="password")

        self.options,self.args=self.op.parse_args()
        self.verify_args(self.options,self.args)
        self.make_connection()
        self.mainPath=os.path.dirname(os.path.abspath(__file__))
        self.last = 0

    def verify_args(self,options,args):
        server=options.server
        port=options.port
        if int(port)>0 and int(port)<65535:
            return True
        else:
            exit("the port is in 0-65535")

    def make_connection(self):
        self.sock=socket.socket()
        self.sock.connect((self.options.server,int(self.options.port)))


    def interactive(self):
        print("begin to interactive.......")

        if self.authenticate():
            while 1:
                cmd_info=input("[%s]"%self.current_dir).strip()# put 12.png images

                cmd_list=cmd_info.split()
                if hasattr(self,cmd_list[0]):
                    func=getattr(self,cmd_list[0])
                    func(*cmd_list)

    def put(self,*cmd_list):
        # put 12.png images
        action,local_path,target_path=cmd_list
        local_path=os.path.join(self.mainPath,local_path)

        file_name=os.path.basename(local_path)
        file_size=os.stat(local_path).st_size

        data={
            "action":"put",
            "file_name":file_name,
            "file_size":file_size,
            "target_path":target_path
        }

        self.sock.send(json.dumps(data).encode("utf8"))

        is_exist=self.sock.recv(1024).decode("utf8")
        ###################################################
        has_sent=0
        if is_exist=="800":
            #文件不完整
            choice=input("the file exist,but not enough,is continue?[Y/N]").strip()
            if choice.upper()=="Y":
                self.sock.sendall("Y".encode("utf8"))
                continue_position=self.sock.recv(1024).decode("utf8")
                has_sent+=int(continue_position)

            else:
                self.sock.sendall("N".encode("utf8"))

        elif is_exist=="801":
            #文件完全存在
           print("the file exist")
           return

        f=open(local_path,"rb")
        f.seek(has_sent)
        while has_sent<file_size:
            data=f.read(1024)
            self.sock.sendall(data)
            has_sent+=len(data)
            self.show_progress(has_sent,file_size)

        f.close()

        print("put success!")

    def show_progress(self,has,total):
        rate=float(has)/float(total)
        rate_num=int(rate*100)
        # if self.last!=rate_num:
        sys.stdout.write("%s%% %s\r"%(rate_num,"#"*rate_num))
        # self.last=rate_num


    def ls(self,*cmd_list):
        data={
            "action":"ls",
        }
        self.sock.sendall(json.dumps(data).encode("utf8"))

        data=self.sock.recv(1024).decode("utf8")
        print(data)


    def cd(self,*cmd_list):
        #cd images
        data={
            "action":"cd",
            "dirname":cmd_list[1]
        }
        self.sock.sendall(json.dumps(data).encode("utf8"))

        data = self.sock.recv(1024).decode("utf8")
        print(os.path.basename(data))
        self.current_dir=os.path.basename(data)


    def mkdir(self,*cmd_list):
        data={
            "action":"mkdir",
            "dirname":cmd_list[1]
        }

        self.sock.sendall(json.dumps(data).encode("utf8"))
        data = self.sock.recv(1024).decode("utf8")






















    def authenticate(self):

        if self.options.username is None or self.options.password is None:
            username=input("username: ")
            password=input("password: ")
            return self.get_auth_result(username,password)

        return self.get_auth_result(self.options.username,self.options.password)

    def response(self):
        data = self.sock.recv(1024).decode("utf8")
        data = json.loads(data)
        return data

    def get_auth_result(self,user,pwd):

        data={
            "action":"auth",
            "username":user,
            "password":pwd
        }

        self.sock.send(json.dumps(data).encode("utf8"))
        response=self.response()
        print("response:",response["status_code"])
        if response["status_code"]==254:
            self.user=user
            self.current_dir=user
            print(STATUS_CODE[254])
            return True
        else:
            print(STATUS_CODE[response["status_code"]])


ch=ClientHandler()

ch.interactive()
ftp_client
技术图片
import optparse
import socketserver

from conf import settings

from core import server


class ArgvHandler():

    def __init__(self):
        self.op=optparse.OptionParser()
        # self.op.add_option("-s","--server",dest="server")
        # self.op.add_option("-P","--port",dest="port")
        options,args=self.op.parse_args()

        self.verify_args(options,args)

    def verify_args(self,options,args):

        cmd=args[0]

        if hasattr(self,cmd):
            func=getattr(self,cmd)
            func()

    def start(self):
        print(" the server is working...")
        s = socketserver.ThreadingTCPServer((settings.IP,settings.PORT),server.ServerHandler)
        s.serve_forever()

    def help(self):
        pass
main
技术图片
import socketserver
import json
import configparser
from  conf import settings

import os

STATUS_CODE  = {

    250 : "Invalid cmd format, e.g: {‘action‘:‘get‘,‘filename‘:‘test.py‘,‘size‘:344}",
    251 : "Invalid cmd ",
    252 : "Invalid auth data",
    253 : "Wrong username or password",
    254 : "Passed authentication",
    255 : "Filename doesn‘t provided",
    256 : "File doesn‘t exist on server",
    257 : "ready to send file",
    258 : "md5 verification",

    800 : "the file exist,but not enough ,is continue? ",
    801 : "the file exist !",
    802 : " ready to receive datas",

    900 : "md5 valdate success"

}




class ServerHandler(socketserver.BaseRequestHandler):

    def handle(self):

        while 1 :
            #conn=self.request
            data=self.request.recv(1024).strip()
            data=json.loads(data.decode("utf8"))

            ‘‘‘
            {"action":"auth",
              "usename":"yuan"
              "pwd":123
            }
            ‘‘‘
            if data.get("action"):

                if hasattr(self,data.get("action")):
                    func=getattr(self,data.get("action"))
                    func(**data)
                else:
                    print("Invalid cmd")
            else:
                print("Invalid cmd")


    def send_response(self,state_code):
        response={"status_code":state_code}
        self.request.sendall(json.dumps(response).encode("utf8"))
    def auth(self,**data):

        username=data["username"]
        password=data["password"]
        user=self.authenticate(username,password)

        if user:
            self.send_response(254)
        else:
            self.send_response(253)


    def authenticate(self,user,pwd):
        cfg=configparser.ConfigParser()
        cfg.read(settings.ACCOUNT_PATH)

        if user in cfg.sections():

            if cfg[user]["Password"]==pwd:
                self.user=user
                self.mainPath= os.path.join(settings.BASE_DIR,"home",self.user)
                print("passed authentication")
                return user

    def put(self,**data):
        print("data",data)
        file_name=data.get("file_name")
        file_size=data.get("file_size")
        target_path=data.get("target_path")

        abs_path=os.path.join(self.mainPath,target_path,file_name)


        ##########################################
        has_received=0

        if os.path.exists(abs_path):
            file_has_size=os.stat(abs_path).st_size
            if file_has_size<file_size:
                #断点续传
                self.request.sendall("800".encode("utf8"))
                choice=self.request.recv(1024).decode("utf8")
                if choice=="Y":
                    self.request.sendall(str(file_has_size).encode("utf8"))
                    has_received+=file_has_size
                    f=open(abs_path,"ab")
                else:
                    f=open(abs_path,"wb")

            else:
                self.request.sendall("801".encode("utf8"))
                return

        else:
            self.request.sendall("802".encode("utf8"))
            f = open(abs_path, "wb")


        while has_received<file_size:
            try:
                data=self.request.recv(1024)
            except Exception as e:
                break
            f.write(data)
            has_received+=len(data)

        f.close()

    def ls(self,**data):

        file_list=os.listdir(self.mainPath)

        file_str="\n".join(file_list)
        if not len(file_list):
            file_str="<empty dir>"
        self.request.sendall(file_str.encode("utf8"))

    def cd(self,**data):

        dirname=data.get("dirname")

        if dirname=="..":
            self.mainPath=os.path.dirname(self.mainPath)
        else:

             self.mainPath=os.path.join(self.mainPath,dirname)

        self.request.sendall(self.mainPath.encode("utf8"))


    def mkdir(self,**data):

        dirname=data.get("dirname")

        path=os.path.join(self.mainPath,dirname)

        if not os.path.exists(path):
            if "/" in dirname:
                os.makedirs(path)
            else:
                os.mkdir(path)
            self.request.sendall("create success".encode("utf8"))
        else:
            self.request.sendall("dirname exist".encode("utf8"))
server

 

技术图片技术图片技术图片

技术图片技术图片技术图片技术图片技术图片

FTP之进度条,cd切换,创建文件夹及校验思路

标签:stat   inpu   targe   dirname   settings   add   show   try   hand   

原文地址:https://www.cnblogs.com/jintian/p/10987110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!