Perl FTP client

Posted on lunedì 20 giugno 2011 by Ivano Binetti

I've written a simple FTP client in perl which allows to integrate ftp into batch scripts.

#!/usr/bin/perl
use Net::FTP;

#variables
$server = $ARGV[1];
$user = $ARGV[3];
$password = $ARGV[5];
$method = $ARGV[7];
$file = $ARGV[9];


#input control
if(@ARGV <1 || $ARGV[0] ne "-s" || $ARGV[2] ne "-u" || $ARGV[4] ne "-p" || $ARGV[6] ne "-m" || $ARGV[8] ne "-f")  {
 usage();
}


#core code
$ftp = Net::FTP->new("$server", Debug => 0)
or die "Cannot connect to $server: $@";
$ftp->login("$user",'$password')
or die "Cannot login ", $ftp->message;


if ($method eq "get") {
 $ftp->get("$file")
 or die "get failed ", $ftp->message;
}


elsif ($method eq "put") {
 $ftp->put("$file")
 or die "put failed ", $ftp->message;
}


else {
usage();
}


$ftp->quit;


#sub defined into input control code
sub usage() {
        print "[-] Usage: <". $0 ."> -s <server> -u <user> -p <password> -m <method> -f <file> \n";
        print "[-] Example: ". $0 ." -s 127.0.0.1 -u user -p password -m get -f test.txt\n";
        exit;
}

Note 1. I've used Net::FTP class/module which can be installed simply calling  "shell subroutine" with the following commands:
  1. perl -MCPAN -e shell
  2. install Net::FTP 
Note 2. As you can imagine, this scripts is only a simple example ad you can add more features to this script to adapt it to your specific context.