Use ftplib to build an FTP-CLIENT in Python

It may seem outdated at the moment, but there are still some “old” generations still in use and “maybe unexpected”, one day we’ll have to work with it.

I have encountered such a case, the client’s system is Windows Server, their current plan to share files is to use FTP Server.

My task is to access the customer’s server, move to the exact folder they specified earlier, search for any newly created files (pushed by the customer), download the file. The processor then accesses the ftp server and uploads the file to a directory they specify, sometimes creating a new directory to execute.

I solved the above problem using python’s ftplib library. Please see my partial listing code below.

Build a ftp server

To continue with the article, if you want to perform the demo according to my code, you can create your own ftp-server following the instructions.

Features of FTP Server:

  • File storage
  • User / password management
  • Assign access rights
  • Provide connection through any port (default: 21):
  • Connect anonymously.
  • Connection identifier: user / password.

FTP Client:

  • Program on the user’s computer, used to connect to the FTP Server

Building FTP-CLIENT using ftplib library

In Python, if you want to connect to FTP, use the ftplib library, this is the default library in the system (available after installing python) so no need to install more.

Initiate connection

from ftplib import FTP

ftp_ip = "your-host-ip"
ftp_usr = "your-username"
ftp_pwd = "your-password"

ftp_client = FTP(ftp_ip)
ftp_client.login(user=ftp_usr, passwd = ftp_pwd)

After successful login, the data returns:

‘230 Logged on’

See ftp-server specifications

ftp_client.welcome

'220-FileZilla Server 0.9.60 beta \ n220-written by Tim Kosse ( tim.kosse@filezilla-project.org ) \ n220 Please visit https://filezilla-project.org/ ’

The commands related to directory / file.

Display the current directory

ftp_client.pwd()

‘/’

Depending on the configuration & authorization of the server according to each login user, the default is to the ftp-server root directory, whose user after logging in will be assigned to a deep internal directory and does not have permission to translate. move out to external folders.

Lists directories / files in the directory connected to

print(ftp_client.retrlines('LIST'))
-rw-r--r-- 1 ftp ftp          11234 May 09 21:39 Doc1.docx
drwxr-xr-x 1 ftp ftp              0 May 09 23:21 Folder1
drwxr-xr-x 1 ftp ftp              0 May 09 21:26 Folder2
-rw-r--r-- 1 ftp ftp           1085 May 09 21:49 sample.ipynb
226 Successfully transferred "/"

Move to another folder from the parent directory:

ftp_client.cwd("Folder1")
'250 CWD successful. "/Folder1" is current directory.'

Note: Only move up to 1 subfolder level

Move to the previous folder.

ftp_client.cwd("..")

'200 CDUP successful. “/” is current directory. ’

Create a new folder

ftp_client.mkd("NewFolder")

'/NewFolder'

Delete directory

ftp_client.rmd("NewFolder")
'250 Directory deleted successfully'

File related command

Check the file size

ftp_client.size("Doc1.docx")
11234

The unit of capacity here is Byte

Delete the file

ftp_client.delete("Doc1.docx")
print(ftp_client.retrlines('LIST'))
drwxr-xr-x 1 ftp ftp              0 May 09 23:21 Folder1
drwxr-xr-x 1 ftp ftp              0 May 09 21:26 Folder2
-rw-r--r-- 1 ftp ftp           1085 May 09 21:49 sample.ipynb
226 Successfully transferred "/"

Upload the file.

  • Conditions upload file from the client must be in the same or deeper than the location where the file runs ftp-client (file code .python) or must point the correct path to the file location.
  • Want to upload to a certain folder, then make a connection to that folder on the server.
from ftplib import FTP
ftp_client = FTP(ftp_ip)
ftp_client.login(user=ftp_usr, passwd = ftp_pwd)

# di chuyển đến thư mục Folder1
ftp_client.cwd("Folder1")
print("before upload\n", ftp_client.retrlines("LIST"))

# read file to send to byte
file_stream = open("sample_9_5.ipynb","rb") 

# send the file       
ftp_client.storbinary("{CMD} {FileName}".
               format(CMD="STOR",FileName="sample_9_5.ipynb"),
               file_stream)     
file_stream.close()                     
print("after upload\n", ftp_client.retrlines("LIST"))
ftp_client.close
drwxr-xr-x 1 ftp ftp              0 May 09 21:31 Folder3
-rw-r--r-- 1 ftp ftp           6174 May 09 21:32 New t.xlsx
-rw-r--r-- 1 ftp ftp           1085 May 09 21:50 sample.ipynb
before upload
 226 Successfully transferred "/Folder1"
drwxr-xr-x 1 ftp ftp              0 May 09 21:31 Folder3
-rw-r--r-- 1 ftp ftp           6174 May 09 21:32 New t.xlsx
-rw-r--r-- 1 ftp ftp           1085 May 09 21:50 sample.ipynb
-rw-r--r-- 1 ftp ftp           1085 May 10 18:59 sample_9_5.ipynb
after upload
 226 Successfully transferred "/Folder1"

Download the file

  • Where to download, run the program file at that location.
  • Connect to the FTP server and download
from ftplib import FTP

ftp_client = FTP(ftp_ip)
ftp_client.login(user=ftp_usr, passwd = ftp_pwd)

ftp_client.cwd("Folder1")
print("before upload\n", ftp_client.retrlines("LIST"))
file_path = "New t.xlsx"
file_name = "New t.xlsx"
file_stream = open(file_path,"wb")         # read file to send to byte
ftp_client.retrbinary('RETR {}'.format(file_name),
               file_stream.write, 1024)
file_stream.close()                     
print("Download OK")
ftp_client.close
drwxr-xr-x 1 ftp ftp              0 May 09 21:31 Folder3
-rw-r--r-- 1 ftp ftp           6174 May 09 21:32 New t.xlsx
-rw-r--r-- 1 ftp ftp           1085 May 09 21:50 sample.ipynb
-rw-r--r-- 1 ftp ftp           1085 May 10 18:59 sample_9_5.ipynb
before upload
 226 Successfully transferred "/Folder1"
Download OK

Close the connection.

Close the connection when done downloading / uploading.

ftp_client.close

<bound method ftp_client.close of <ftplib.FTP object at 0x000001F61AFE65F8 >>

In addition to the basic commands above, you can refer to the other commands of ftplib from the following link: https://docs.python.org/3/library/ftplib.html

#python #programming

Use ftplib to build an FTP-CLIENT in Python
19.75 GEEK