Implementing the FTP Service feature instance (client) using Python3

Source: Internet
Author: User
Tags ftp client
This article is mainly for you to introduce the PYTHON3 implementation of the FTP service function, the corresponding code of the client, with a certain reference value, interested in small partners can refer to

Client main code:


#Author by Andy#_*_ coding:utf-8 _*_ "This program was used to create a FTP client ' import Socket,os,json,time,hashlib,sy Sclass ftp_client (object): Def init (self): Self.client = Socket.socket () def: msg = "Useage:ls pwd CD D IR (example:/.../var) put filename rm filename get filename mkdir directory name ' Print (MSG) def connect (self, Addr,port): Self.client.connect ((addr,port)) def auth (self): M = hashlib.md5 () Username = input ("Please enter user name:"). Strip () m.u    Pdate (Input ("Please enter password:"). Strip (). Encode ()) password = m.hexdigest () User_info = {' action ': ' auth ', ' username ': username, ' Password ':p assword} self.client.send (Json.dumps (User_info). Encode (' Utf-8 ')) Server_response = Self.client.recv ( Decode () # print (Server_response) return server_response def Interactive (self): while true:msg = input ("&GT;&G T;>: "). Strip () If not msg:print (" Cannot send empty content! "). ") Continue cmd = Msg.split () [0] if hasattr (self,cmd): func = GetAttr (self,cmd) func (msg) Else:self.help () Continue def put (Self,*args): Cmd_split = Args[0].split () If Len (cmd_split) > 1:filena me = cmd_split[1] if os.path.isfile (filename): filesize = os.stat (filename). st_size File_info = {"Action": "Pu T "," filename ": filename," size ": FileSize," overriding ": ' True '} self.client.send (Json.dumps (file_info).    Encode (' Utf-8 ')) #防止粘包, wait for the server to confirm.    Request_code = {' $ ': ' Ready to recceive data! ', ' data! ': ' Isn't ready to received ' } Server_response = Self.client.recv (1024x768). Decode () if server_response = = ' $ ': F = open (filename, "RB") Sen D_size = 0 start_time = time.time () for line on F:self.client.send (line) Send_size + = len (line) se nd_percentage = Int ((send_size/filesize) * +) while true:progress = (' \ r uploaded%smb (%s%%) '% (round (send_size /102400, 2), send_percentage). Encode (' Utf-8 ') os.write (1, Progress) Sys.stdout.flush () TIME.SL EEP (0.00Else:end_time = Time.time () time_use = Int (end_time-start_time) print ("\nfile%s has      Been sent successfully! "% filename" print (' \ n average download speed%s MB/s)% (round (round (send_size/102400, 2)/Time_use, 2)))     F.close () else:print ("Sever isn ' t ready to receive data!") Time.sleep (Ten) start_time = Time.time () f = open (filename, "RB") Send_size = 0 for line in F:SELF.C Lient.send (line) Send_size + = Len (line) # Print (send_size) while true:send_percentage = Int (sen         d_size/filesize) * progress = (' \ R ' uploaded%smb (%s%%) '% (round (send_size/102400, 2), send_percentage)). Encode (       ' Utf-8 ') os.write (1, Progress) Sys.stdout.flush () # time.sleep (0.0001) Break else:  End_time = Time.time () time_use = Int (end_time-start_time) print ("File%s has been sent successfully!"% FileName) print (' \ n average download speed%s MB/s "% (round (round (send_size/102(2)/Time_use, 2)) F.close () else:print ("File%s is not exit!"%filename) else:self.help () def LS (sel F,*args): Cmd_split = Args[0].split () # Print (cmd_split) If Len (cmd_split) > 1:path = cmd_split[1] elif len (cmd_  Split) = = 1:path = '. ' Request_info = {' action ': ' ls ', ' Path ': path} self.client.send (Json.dumps (Request_info). Encode (' Utf-8 ')) sever_re Sponse = Self.client.recv (1024x768). Decode () print (sever_response) def pwd (Self,*args): Cmd_split = Args[0].split () If Len (   cmd_split) = = 1:request_info = {' action ': ' pwd ',} self.client.send (Json.dumps (Request_info). Encode ("Utf-8")) Server_response = Self.client.recv (1024x768). Decode () print (Server_response) else:self.help () def get (Self,*args): cmd _split = Args[0].split () If Len (cmd_split) > 1:filename = cmd_split[1] File_info = {"Action": "Get", "fi Lename ": filename," overriding ": ' True '} self.client.send (Json.dumps (File_info). Encode (' Utf-8 ')) server_resPonse = Self.client.recv (1024x768). Decode () #服务器反馈文件是否存在 self.client.send (' 0 '. Encode (' Utf-8 ')) if server_response = = ' 0 ': file_size = Int (SELF.CLIENT.RECV (1024x768). Decode ()) # Print (file_size) self.client.send (' 0 '. Encode (' Utf-8 ')) #确认开始传输 Data if Os.path.isfile (filename): filename = filename+ '. New ' F = open (filename, ' wb ') receive_size = 0 m = ha  SHLIB.MD5 () start_time = Time.time () while receive_size < file_size:if file_size-receive_size > 1024: # You also need to receive more than 1 times size = Else:size = File_size-receive_size data = self.client.recv (size) m.update (d  ATA) Receive_size + = len (data) Data_percent=int ((receive_size/file_size) * +) F.write (data) Progress = (' \ R '%smb (%s%%) '% (round (receive_size/102400,2), data_percent)). Encode (' Utf-8 ') os.write (1,progress) sys.stdout. Flush () time.sleep (0.0001) else:end_time = Time.time () time_use = Int (end_time-start_time) print (' \ n Average download speed%s MB/s '% (round (ROund (receive_size/102400,2)/time_use,2)) Md5_server = Self.client.recv (1024x768). Decode () Md5_client = M.hexdigest () Print (' File check, please wait ... ') time.sleep (0.3) if md5_server = = Md5_client:print (' File OK. ') else:print (' The file does not match the server MD5 value, please confirm!    ') else:print (' File not found! ') Client.interactive () else:self.help () def RM (Self,*args): Cmd_split = Args[0].split () If Len (cmd_split) > 1:fi Lename = cmd_split[1] Request_info = {' action ': ' RM ', ' filename ': filename, ' prompt ': ' Y '} self.client.send (Json.dumps (Request_info). Encode ("Utf-8")) Server_response = Self.client.recv (10240). Decode () Request_code = {' 0 ': ' Confirm to deleted ', ' 1 ': ' Cancel to deleted ' If server_response = = ' 0 ': Confirm = input ("Please confirm that the file is really deleted:") I    f confirm = = ' Y ' or confirm = = ' Y ': self.client.send (' 0 '. Encode ("Utf-8")) Print (SELF.CLIENT.RECV (1024x768). Decode ()) Else:self.client.send (' 1 '. Encode ("Utf-8")) Print (SELF.CLIENT.RECV (1024x768). Decode()) Else:print (' File not found! ') Client.interactive () else:self.help () def CD (Self,*args): Cmd_split = Args[0].split () If Len (cmd_split) > 1:pa  th = cmd_split[1] elif len (cmd_split) = = 1:path = '. ' Request_info = {' Action ': ' CD ', ' Path ':p ath} self.client.send (Json.dumps (Request_info). Encode ("Utf-8") server_res Ponse = Self.client.recv (10240). Decode () print (server_response) def mkdir (Self,*args): Request_code = {' 0 ': ' Director  Y have been made! ', ' 1 ': ' Directory is aleady exist! ' } Cmd_split = Args[0].split () If Len (cmd_split) > 1:dir_name = cmd_split[1] Request_info = {' action ': ' mkdir ' , ' Dir_name ': Dir_name} self.client.send (Json.dumps (Request_info). Encode ("Utf-8")) Server_response = Self.client   . recv (1024x768). Decode () if server_response = = ' 0 ': print (' Directory has been made! ')  Else:print (' Directory is aleady exist! ') Else:self.help () # def Touch (Self,*args):d EF Run (): client = Ftp_client () # Client.connect (' 10.1.2.3 ', 6969) Addr = input ("Enter server IP:"). Strip () port = Int (Input ("Enter port number:"). Strip ()) Client.connect (Addr,port) while True:if Client.auth () = = ' 0 ': print ("Welcome ...") client.interactive () Break Else:print ("Username or password Error! ") Continue

Directory structure:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.