Sunday, November 17, 2024
Google search engine
HomeLanguagesHow to List all Files and Directories in FTP Server using Python?

How to List all Files and Directories in FTP Server using Python?

FTP ( File Transfer Protocol ) is set of rules that computer follows to transfer files across computer network. It is TCP/IP based protocol. FTP lets clients share files. FTP is less secure because of files are shared as plain text without any encryption across the network. 

It is possible using python to retrieve list of file and directories from FTP server using its in-built ftplib module. ftplib is a pre-installed python package, which enables us to implement client side FTP protocol and in order to use it we simply have to import it like any other module. Basic approach to extract list or directories remains the same.

Approach

  • Import module
  • Connect to host on default port 

Syntax:

FTP(host=”, user=”, passwd=”, acct=”, timeout=None, source_address=None, *, encoding=’utf-8′)

  • Log in to the server using login() function

Syntax:

login(user=’anonymous’, passwd=”, acct=”)

  • Retrieve files and directories accordingly.
  • Close connection

Method 1: using retrlines()

Files and directories can be listed with retrlines() function. It returns filename, modified time, file size, owner, file type, permissions and Mode.

Syntax:

retrlines(cmd, callback=None)

Passing ‘LIST’ in this function retrieves files and information about those files.

Program:

Python3




from ftplib import FTP
  
ftp = FTP('ftp.us.debian.org')
  
ftp.login()
  
# changing directory
ftp.cwd('debian')
  
ftp.retrlines('LIST')
  
ftp.quit()


Output:

fig: 2

This function could also be user to search for a file or directory. Search query can be entered in between asterisk(*).

Syntax:

ftp.retrlines(‘LIST *query*’)

Program: listing file names starting with “README”.

Python3




from ftplib import FTP
  
ftp = FTP('ftp.us.debian.org')
  
ftp.login()
  
# changing directory
ftp.cwd('debian')
  
ftp.retrlines('LIST *README*')
  
ftp.quit()


Output:

fig: 3

Method 2: Using dir()

Files and directories can be listed with dir(). It returns filename, modified time, file size, owner, file type, permissions and Mode.

Syntax:

ftp.dir()

Program:

Python3




from ftplib import FTP
  
ftp = FTP('ftp.us.debian.org')
  
ftp.login()
  
# changing directory
ftp.cwd('debian')
  
ftp.dir()
  
ftp.quit()


Output:

fig: 4

Method 3: Using nlst()

Files and directories can be listed with nlst(). It returns name of files and directories of list type.

Syntax:

ftp.nlst()

Program:

Python3




from ftplib import FTP
  
ftp = FTP('ftp.us.debian.org')
  
ftp.login()
  
# changing directory
ftp.cwd('debian')
  
ftp.nlst()
  
ftp.quit()


Output:

fig: 5

RELATED ARTICLES

Most Popular

Recent Comments