Friday, October 24, 2014

Copying files to and from a remote server using FTP in Perl

Following is a simple script to copy files to and from a remote server in the network using FTP.

#!/usr/bin/perl

use Net::FTP; # required module for FTP

my $ftp = Net::FTP->new('remoteserver ipaddress') or die "Cannot connect : $@"; # Connect to remote server for FTP

$ftp->login('username','password') or die "Cannot login :", $ftp->message; # Login to remote server using FTP username and password

$ftp->cwd("/var/www/test") or die "Cannot change directory :", $ftp->message; # Change working directory in the remote server for file transfer

$ftp->get("data.csv") or die "Cannot get file :", $ftp->message; # Fetching a file from the working directory (mentioned in the previous line using cwd) of remote server, to the working directory of the script in the running server

$ftp->put("/var/www/html/test.html") or die "Cannot put file :", $ftp->message; # Copying a file from the specified path of the script in the running server, to the working directory (mentioned in the previous line using cwd) of remote server

$ftp->quit(); # Closing the ftp connection



Output:
-------
On execution of the script, a FTP connection to the remote server will be opened and 'data.csv' file from '/var/www/test' location of the remote server will be copied to the working directory of the script running server and then '/var/www/html/test.html' from the specified location of the script running server will be copied to the '/var/www/test' location of the remote server.