How to write automated FTP script in Linux

Comments Off on How to write automated FTP script in Linux

In this article I will show you how to write automated FTP script in Linux. File Transfer Protocol (FTP) is typically used to copy files from one computer to another. The automated FTP script is mostly useful when you are a server administrator and you are maintaining many servers and you need to take backup or transfer files among them at regular basis. There are other file transfer protocols available but FTP uses port 21/20 which remains by default open in most of the routers and firewalls. Moreover it is the fastest and widely acceptable protocol. I am not going to discuss basic FTP commands here and assume that the reader are well conversant with FTP basic commands.
I am showing a FTP shell script which I tested in Red hat and Centos. I think it will work without any problem in other Linux distributions too. Here is the script:

#!/bin/bash
remote_server="10.10.4.16"
ftp_local_directory="/u02/cbscdr"
ftp_remote_directory="/u02/reporter/cbscdr"
yesterday=`date +%Y%m%d --date=yesterday`
data_file=data${yesterday}*
ftp -i -v -n $remote_server << FTP
user reporter reporter
lcd $ftp_local_directory
cd $ftp_remote_directory
mget $data_file
quit
FTP

In the above script, I am copying files from server 10.10.4.16 where files name contain date. The file name like data20151105_00010110.csv and there are lot of files in the remote server whose prefix is data{date}{sequential number}. I am copying all files of yesterday. You can schedule the FTP script in crontab ( 01 10 * * * /home/oracle/scripts/ftp.sh). Here goes the commands and variables used in script

remote_server -Remote server from which files are being copied
ftp_local_directory– local directory in which files are being copied
mget – command to copy file from remote server.
yesterday– contain previous day in {year}{month}{day} form e.g. 20151105
data_file – contain file prefix e.g. data20151105*

Conclusion
To write an automated FTP script is very easy however very useful for copying and backing up files across multiple server. Especially who are working as a server administrator, it makes their work easier and smooth. Unlike other file transfer protocol FTP generally is allowed across the network equipment.

You can download the script from ftp.sh