Setting up an FTP server on Ubuntu using vsftpd and connecting to it using Python's ftplib module
I know what you're thinking, "Who in the world still uses FTP these days?". If you were born after year 2000, you may not even have heard of FTP before.
FTP (File Transfer Protocol) was a popular way to share files back in the AOL days. People will set up these FTP servers where you can upload and download files. I remember spending so much time in chat rooms during my teenage years asking around for FTP hosts and credentials where I can download music and movies. I think there were even servers back then that require you to upload something before you can download to encourage sharing. There were also those which require payment to access.
Nowadays, with BitTorrent sites and cloud storage services such as Dropbox, Amazon S3, and Google Drive, it just seems unnecessary to use FTP anymore. However, there are still a surprising number of companies who rely heavily on it to run their businesses.
I'm currently working on a new Shopify app where we provide an option to send files via FTP. After reading reviews of similar apps, it was clear that many people still use it to share files with their vendors/partners.
Below is a quick tutorial on how to set up an FTP server using vsftpd on Ubuntu 14.04 and how to connect to it using Python's built-in ftplib module.
Install vsftpd
sudo apt-get install vsftpd
Update the vsftpd configuration
In /etc/vsftpd.conf, apply the following settings:
# (Uncomment) Allow local users to log in. local_enable=YES # (Uncomment) Enable writing. write_enable=YES # (Uncomment) Restrict local users to their home directories. chroot_local_user=YES # (Update). pam_service_name=ftp # (Add to end of config). allow_writeable_chroot=YES pasv_address=public_ip_address_of_server
Create an FTP user with a nologin shell for additional security
sudo useradd -m ftpuser1 -s /usr/sbin/nologin sudo passwd ftpuser1
Allow login access for the nologin shell
Update /etc/shells by adding /usr/bin/nologin at the end of the file.
Restart vsftpd
sudo service vsftpd restart
Accessing the FTP server using Python's ftplib module
Note that the code below was tested using Python 3.5.
from ftplib import FTP with FTP('ftp.example.com') as ftp: ftp.login(username, password) ftp.dir() # List the files in the user's home directory.
Enabling SSL/TLS
To enable SSL/TLS, we'll need to add some additional lines to the /etc/vsftpd.conf file.
# (Add to end of config). ssl_enable=YES require_ssl_reuse=NO
Restart vsftpd again.
sudo service vsftpd restart
Accessing the FTP server with TLS using Python's ftplib module
Once again, the code below was tested with Python 3.5.
from ftplib import FTP_TLS ftps = FTP_TLS('ftp.example.com') ftps.login(username, password) ftps.prot_p() ftps.dir() ftps.quit()
That's it!
Tags: howto, linux, python, tech, software development, networking