Perl Script to download files from ftp in asyn manner.

It is very common that sometimes we have to download files from ftp and those files are huge and it will elapse more than hours and it is very tedious if have to download them one by one manually.

Below is sample script written in perl that can help download files from ftp automatically with Perl fork function.

#! /usr/bin/perl

use strict;
use Net::FTP;

print "**Ensure that your dir is writable. Press ' y ' to continue ' n ' to exit**\n";
my $inp=<STDIN>;
chomp($inp);
$inp=lc($inp);

if($inp ne 'y') {
print" Quit ... \n";
exit(0);
}

my $uname;
my $passwd;
#Here supposed that your file directory in ftp is
# /filenumber/file
# for example, if you want to download file under dir 123, then it is under /123/* in your ftp
my @filesnumbers1 =
("123","456","789"
);
my @filesnumbers2 =
("1234","4567","68787"
);
my @filesnumbers3 =
("434545","647667","7567577"
);
my @filesnumbers4 =
("756767","990788","4778"
);
my @filesnumbers5 =
("68895","42476878","98964564"
);
my @filesnumbers6 =
("5354767","98945646"
);

system('stty','-echo');
print "\t*****Enter ftp username********\n";
chomp($uname=<STDIN>);
system('stty','echo');

system('stty','-echo');
print "\t*****Enter ftp password********\n";
chomp($passwd=<STDIN>);
system('stty','echo');

##############
# Here we use fork provided by Perl to download in async manner.
#
print "Starting main program\n";
my @childs;

for ( my $count = 1; $count <= 6; $count++) {
my $pid = fork();
if ($pid) {
# parent
push(@childs, $pid);
} elsif ($pid == 0) {
# child
if ($count == 1){
download(@filesnumbers1);
} elsif ($count == 2){
download(@filesnumbers2);
} elsif ($count == 3){
download(@filesnumbers3);
} elsif ($count == 4){
download(@filesnumbers4);
} elsif ($count == 5){
download(@filesnumbers5);
} elsif ($count == 6){
download(@filesnumbers6);
} else {
}
exit 0;
} else {
die "couldnt fork: $!\n";
}

}

foreach (@childs) {
my $tmp = waitpid($_, 0);
print "done with pid $tmp\n";

}

print "End of main program\n";
##############

sub download{
my @filesnumbers = @_ ;
my $newerr = 0;

foreach my $filehander(@filesnumbers) {

# here we use the Net::FTP from Perl
my $ftp=Net::FTP->new("ftpaddress.ftpserver.com",Port=>1234) or $newerr=1;
if($newerr){
print "can not ftp ...\n";
exit(1);
}

$ftp->login("$uname","$passwd") or $newerr=1;
if($newerr){
print "Uname or Passwd error: $!";
exit(1);
}

print "Downloading filehander number $filehander ... \n";
$ftp->cwd($filehander) or $newerr=1;
$ftp->binary;
my @list = $ftp->ls;
for (@list) {
print " --- Getting zip file: $_ ---\n";
$ftp->get("$_") or die "Error:",$ftp->message;
}
$ftp->close or die "Error:", $ftp->message;
}
}

# More details, http://perldoc.perl.org/perlfork.html

http://perldoc.perl.org/Net/FTP.html