Python implements ftp file transfer function

The examples in this article share the specific code of python to realize ftp file transfer for your reference. The specific content is as follows

The main steps can be divided into the following steps:

  1. Read file name
  2. Check if the file exists
  3. open a file
  4. Detect file size
  5. Send the file size and md5 value to the client
  6. Wait for client confirmation
  7. Start sending data while reading

Server-side code:

import socket,os,time
import hashlib
 
server =socket.socket()
server.bind(('0.0.0.0',6666))
server.listen()print("wait....")while True:
 conn,addr = server.accept()print("new conn:",conn)while True:
 data = conn.recv(1024)if not data:print("client is disconnection")break
 cmd,filename = data.decode().split() #Record instructions and file names
 print(filename)
 # Determine whether the file exists in the current directory, and it must be a file, not a directory
 if os.path.isfile(filename):
 f =open(filename,'rb')
 # m = hashlib.md5() #Create md5
 file_size = os.stat(filename).st_size #stat()Can return the size of the file
 conn.send((str(file_size)).encode()) #Send file size
 conn.recv(1024) #Waiting for return information
 for line in f:
 # m.updata(line) 
 conn.send(line)
 # print("file md5",m.hexdigest()) #Print md5 value
 f.close()

Client code:

# Author: zjt
import socket
 
client = socket.socket()
 
client.connect(("0.0.0.0",6666))while True:
 cmd =input("   :").strip()iflen(cmd)==0:continueif cmd.startswith("get"):
 client.send(cmd.encode())
 server_response = client.recv(1024)print("server response: ",server_response)
 client.send(b"ready to recv file")
 
 # Start receiving files
 file_total_size =int(server_response.decode())
 received_size =0 #Record the size of the received file
 filename = cmd.split()[1]
 # Because the two directories are consistent, the received file name cannot be the same as the original file
 f =open(filename+".new","wb")while received_size < file_total_size:
 data = client.recv(1024)
 received_size +=len(data)
 f.write(data)print("total:",file_total_size," present: ",received_size)else:print("file has received done!")
 f.close()
 
client.close()

Use 80M file transfer test, the effect is as follows:

**Program upgrade: **

The previous code has not added md5 for verification, now the code is upgraded

**Server-side code: **

import socket,os,time
import hashlib
 
server =socket.socket()
server.bind(('0.0.0.0',8888))
server.listen()print("wait....")while True:
 conn,addr = server.accept()print("new conn:",conn)while True:
 data = conn.recv(1024)if not data:print("client is disconnection")break
 cmd,filename = data.decode().split() #Record instructions and file names
 print(filename)
 # Determine whether the file exists in the current directory, and it must be a file, not a directory
 if os.path.isfile(filename):
 f =open(filename,'rb')
 m = hashlib.md5() #Create md5
 file_size = os.stat(filename).st_size #stat()Can return the size of the file
 conn.send((str(file_size)).encode()) #Send file size
 conn.recv(1024) #Waiting for return information
 for line in f:
 m.update(line)
 conn.send(line)print("file md5",m.hexdigest()) #Print md5 value
 
 f.close()
 conn.send(m.hexdigest().encode()) #Send md5
 
 print("I really sent it",m.hexdigest().encode())print("send done")
 
server.close()

Client code:

import socket
import hashlib
client = socket.socket()
client.connect(("0.0.0.0",8888))while True:
 cmd =input("   :").strip()iflen(cmd)==0:continueif cmd.startswith("get"):
 client.send(cmd.encode())
 server_response = client.recv(1024)print("server response: ",server_response)
 client.send(b"ready to recv file")
 # Start receiving files
 file_total_size =int(server_response.decode())
 received_size =0 #Record the size of the received file
 filename = cmd.split()[1]
 # Because the two directories are consistent, the received file name cannot be the same as the original file
 f =open(filename+".new","wb")
 m = hashlib.md5()while received_size < file_total_size:
 data = client.recv(1024)
 received_size +=len(data)
 m.update(data)
 f.write(data)
 # print("total:",file_total_size," present: ",received_size)else:
 new_file_md5 = m.hexdigest()print("client file md5:",new_file_md5)print("file has received done!")print("total:",file_total_size," present: ",received_size)
 f.close()
 sever_file_md5 = client.recv(1024)print("client file md5:",new_file_md5)print("server file md5:",sever_file_md5)
client.close()

The two programs are run in the linux environment and the results are as follows:

It can be seen that the file size has become a little larger after the transfer, and the values before and after md5 are also different, indicating that the file transfer has changed.

Now let's talk about the program running in the windows environment, the results are as follows:

At this point, you can see that there is no problem on windows, the file size is the same, and the md5 value is also the same.

Cause Analysis:

This happens because when running on linux, a stickable packet occurred during the last file transfer and the md5 value sent, resulting in the last time the file was received, and the md5 data was sent together. And the client is also treated as a piece of received information, all received. Therefore, the client does not receive the md5 value from the server, and the little extra is the md5 value.

Solution:

When receiving files, determine how many files are currently remaining to be received. If it is greater than 1024, receive files of 1024 size, otherwise, only receive all the remaining files to prevent the last time receiving redundant data.

Only need to modify the client code, the modified code is as follows:

import socket
import hashlib
client = socket.socket()
client.connect(("0.0.0.0",8888))while True:
 cmd =input("   :").strip()iflen(cmd)==0:continueif cmd.startswith("get"):
 client.send(cmd.encode())
 server_response = client.recv(1024)print("server response: ",server_response)
 client.send(b"ready to recv file")
 # Start receiving files
 file_total_size =int(server_response.decode())
 received_size =0 #Record the size of the received file
 filename = cmd.split()[1]
 f =open(filename+".new","wb")
 m = hashlib.md5()while received_size < file_total_size:
 # Add a judgment so that as much as there is left in the last time, you can receive as much as possible to avoid sticky packets
 if file_total_size - received_size   1024:
 size =1024else: #The last time, how much is left
 size = file_total_size - received_size
 data = client.recv(size)
 received_size +=len(data)
 m.update(data)
 f.write(data)else:
 new_file_md5 = m.hexdigest()print("client file md5:",new_file_md5)print("file has received done!")print("total:",file_total_size," present: ",received_size)print("Next sentence close the file")
 f.close()print("Start receiving md5") 
 sever_file_md5 = client.recv(1024)print("client file md5:",new_file_md5)print("server file md5:",sever_file_md5)
client.close()

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

Python implements ftp file transfer function
Python implements TCP file transfer
How Python implements FTP function
Python tornado upload file function
Python implements image stitching function
How Python implements the mail function
Python implements AI face change function
How Python implements the timer function
Python file operation
python_ file processing
Python enumerate() function
Python function buffer
Python implements Super Mario
Python implements tic-tac-toe game
Python custom function basics
Join function in Python
Python built-in function -compile()
Python implements man-machine gobang
Python function basic learning
Python data analysis-apply function
Python implements image stitching
Python3 built-in function table.md
Python implements scanning tools
Python Print print timer function
Python implements threshold regression
Python implements minesweeper games
Python implements FTP to upload files in a loop
Python implements electronic dictionary
Python implements guessing game
Python defines a function method
Python implements simple tank battle
Python implements udp chat window
Python realizes online translation function
Python implements a guessing game
Python implements parking management system
Python implements digital bomb game
Python numpy implements rolling case
OpenCV Python implements puzzle games
Python implements simple tic-tac-toe game
Python implements password strength verification
Python implements car management system
Python implements code block folding
Python implements panoramic image stitching
Python magic function eval () learning
Python implements SMTP mail sending
Python implements multi-dimensional array sorting
Python implements mean-shift clustering algorithm
Python implements verification code recognition
Python implements gradient descent method
Python implements text version minesweeper
Quick start Python file operation
Python high-order function usage summary!
Python implements the brick-and-mortar game