Copy files over FTP using Python
FTP is a common protocol used by most sysadmins to copy files over a network to remote servers either for backup or for some other reason.Python has an inbuilt module for working FTP. A Microsoft FTP server or any Linux based FTP server such as VSFTP or Pure-FTPD will suffice for the tutorial.
#!/usr/bin/env python import os import ftplib file_to_upload = /root/backup/home.tar.gz server = '192.168.36.8' username = 'test_account' password = 'welcome123' ftp_connection = ftplib.FTP(server, username, password) remote_path = "/ftp/" ftp_connection.cwd(remote_path) fh = open(file_to_upload, 'rb') ftp_connection.storbinary('STOR %s' % os.path.basename(file_to_upload), fh) fh.close()
We first import the ftplib and os modules
We Then define our server parameters such as server running the FTP service,username and password.
ftp_connection = ftplib.FTP(server, username, password) – We define ftp_connection as a variable to hold the conenction to our FTP server which is sitting somewhere.
remote_path = “/ftp/” – A variable for the remote Directory.
ftp_connection.cwd(remote_path) – After connection is successful, we change to a directory on the remote server.
fh = open(file_to_upload, ‘rb’) – we declare a variable fh to hold file we will be copying.
ftp_connection.storbinary(‘STOR %s’ % os.path.basename(file_to_upload), fh) – This will actually copy the file to the server using the STOR parameter as we are storing.The os.path.basename ensure the last part of the path which is the actual file we want to copy is copied.
fh.close() – This closes the ftp connection when copying is done.
You can save the file the run it or set a cron to run it on regular basis