Filed Under: Python

Today we will learn about python ftp operations. FTP is an acronym for File Transfer Protocol. Just like what it sounds, this protocol is used to transfer files across a network from source to destination machine.

In this post on python ftp module, we will see how to connect to a FTP server, upload & download files and much more. Let’s get started.

Python ftp

With Python, ftplib module provides all the functions which we might need to perform actions across the FTP protocol. Let’s start exploring this lesson with simple connection attempt.

Connecting to an FTP server with login() function

We will start by making a connection to an FTP server. We will use a server publicly available for usage, ftp.cse.buffalo.edu. Feel free to choose any server, just make sure you select the right server otherwise you will face connection errors.

We will write a simple script to connect to the said server:


from ftplib import FTP

# Host to connect to
host = 'ftp.cse.buffalo.edu'

# Make an Python FTP object and anonymously login
ftp = FTP(host)
print(ftp.login())

See how we can login without a username and a password? That is supported by few servers only. Let us see the output:
ftplib-connection
In this example, we started by importing a single class from complete module called FTP. We used its object to connect to a host and anonymously login to the server.
Of course, we didn’t pass a port to connect. This means just like any other request that this will arrive at the default port of the server. To change this, specify the port for the connection as well:


from ftplib import FTP

# Host to connect to
host = 'ftp.cse.buffalo.edu'
port = 8099

# Make an FTP object and anonymously login
ftp = FTP(host, port)
print(ftp.login())

Do take care that the port you’re connecting to actually supports an incoming FTP connection.

Feel welcomed with getwelcome() function

A server can make you feel welcomed by returning a message. This message can be obtained using getwelcome() function. Easy to use, let’s put it in an example:


from ftplib import FTP

# Host to connect to
host = 'ftp.cse.buffalo.edu'

# Make an FTP object and anonymously login
ftp = FTP(host)
print(ftp.login())
print(ftp.getwelcome())

Output for this script will just show a simple message which can be anything:
ftp-getwelcome

Present Directory with pwd() function

We can get the path of presently working directory of the server our connection is present at currently:


from ftplib import FTP

host = 'ftp.cse.buffalo.edu'
ftp = FTP(host)
ftp.login()

ftp.cwd('mirror')
print(ftp.pwd())

Output for this script will just show present working directory:
ftplib-pwd

Accessing Directories with retrlines() function

Now, just like an open SSH shell, we can use ftplib to access the directories on the server, navigate through them and change them based on needs.


from ftplib import FTP

# Host to connect to
host = 'ftp.cse.buffalo.edu'

# Make an FTP object and anonymously login
ftp = FTP(host)
print(ftp.login())

# List directories in current path
print(ftp.retrlines('LIST'))

Look at the last line, we used the retrlines(...) function to list the current directories. Output for this script will be:
ftplib-directories

Changing Directories with cwd() function

In above example, we listed the directories our script was currently accessing. To add, we can see current directory easily as:


from ftplib import FTP

# Host to connect to
host = 'ftp.cse.buffalo.edu'

# Make an FTP object and anonymously login
ftp = FTP(host)
print(ftp.login())

# List directories in current path
print(ftp.retrlines('LIST'))

# Change into one of the sub-directories
ftp.cwd('mirror')
print(ftp.retrlines('LIST'))

Here, we’re switching to one of the sub-directories we noticed in an earlier run and we get the following results:
ftplib-cwd
The LIST attribute passed just pulls out the files and folders in current directory along with their information, which we then print.

Send command to server with sendcmd() function

Using the sendcmd() function, we can send a simple String command to the server and obtain the String response. For an example, we will send a command STAT which can check the status fo a server:


from ftplib import FTP

host = 'ftp.cse.buffalo.edu'
ftp = FTP(host)
print(ftp.login())

# Check server status
print(ftp.sendcmd('STAT'))

When we run this script, we see the complete output on our own console:
ftplib-sendcmd

Downloading files with retrbinary() function

Using ftpliob module, we can even download files locally. It is worth noticing that to do this, you must have proper access to a server and directories and file names and exact paths should be known.

We will simply access a file on server and download it locally:


from ftplib import FTP

host = 'ftp.cse.buffalo.edu'
ftp = FTP(host)
ftp.login()

ftp.cwd('CSE421')
print(ftp.retrlines('LIST'))

out = '/Users/shubham/README.txt'
with open(out, 'wb') as f:
    ftp.retrbinary('RETR ' + 'README.txt', f.write)

I add some print statements in between to make the output a bit more clear. Let’s run this program now:
python ftp download file
And here is the file which was downloaded:
downloaded-file
Please note that you will need to modify the location of file download based on your local machine path before running this code.

Close connection with close() function

We should close the ftp connection once we’re done with any tasks needed to do be done:


from ftplib import FTP

host = 'ftp.cse.buffalo.edu'
ftp = FTP(host)
ftp.login()

ftp.cwd('mirror')
print(ftp.pwd())

ftp.close()
print('Connection closed.')

Output for this script will just show present working directory:
ftplib-close
Remember, we cannot open a closed python ftp connection again.

In this lesson, we learned about various ways through which we can access an FTP server and play with directories and manage it completely.

Reference: API Doc

Comments

  1. Dauren says:

    ftp.cwd('CSE421')
    print(ftp.retrlines('LIST'))

    how to show in the cycle just filename and filesize
    for i in files:

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages