|
Softpanorama |
May the source be with you, but remember the KISS principle ;-)
Softpanorama Search
|
| News | Recommended Links | Reference | Sort in Perl |
| Regular expressions | History | Humor | Etc |
Using Net::FTP, which is a standard Perl module, you can write simple FTP clients that transfer files. Here is an example of a client that connects to a remote FTP server and gets a file from the server:
Simple example:
#!/usr/local/bin/perl -w use Net::FTP; $hostname = 'yourhost'; $username = 'youname'; $password = 'yourpass'; # Hardcode the directory and filename to get $home = `pwd`; $target='/home/usr/public_html'; $filename = 'index.shtml'; # Open the connection to the host
$ftp = Net::FTP->new($hostname) or die("Can't connect to the server\n"); # construct object
$ftp->login($username, $password) or die("Can't login to the account $username"); # log in
print "Connected to $username\@$hostname \n";
# Now let's put file to the ftp servere and leave
put_file($file);
$ftp->quit;
exit;
sub put_file {
$filename=substr($file, $last);
$path=substr($file,0,$last);
$ftp->cwd($path); $ftp->put($filename);
@ls=$ftp->ls("$path/$filename";
if (index (@ls[0]),$filename) > -1) {
print "File $filename was transferred successfully to the $path directory\n";
return 1;
} else {
print File transfer of $filename faled\n";
return 0; }
More complex variant
FTP clients have also been integrated with most World Wide Web browsers, using ftp:// in place of http://. When the URL points to a directory, the browser displays a listing of the directory, where each filename is a link to that file. When the URL points directly to a file, the remote file is downloaded.#!/usr/local/bin/perl -w use Net::FTP; $hostname = 'yourhost'; $username = 'youname'; $password = 'yourpass'; # Hardcode the directory and filename to get $target='/home/usr/public_html'; $filename = 'index.shtml'; # Open the connection to the hostconnect($hostname,$username,$password);# Now let's put files to the ftp servere and leavewhile($file=<SYSIN>) {chomp($file);$last=rindex($file,"/"); unless($last>0) {print "wrong file $file\n";next;} put_file($file);} # for $ftp->quit;exit;sub connect{$ertype=''; $ftp = Net::FTP->new($hostname) or die("Can't' connect to the server\n"); # construct object $ftp->login($username, $password) or die("Can't login to the account $username"); # log inprint "Connected to $username\@$hostname \n";}sub put_file{my ertype='';$filename=substr($file, $last);$path=substr($file,0,$last);$ftp->cwd($path) || ertype="path $path" doe not exit of target computer\n";return 0 if ($ertype);$ftp->put($filename);if (index ($ftp->ls("$path/$filename"),$filename) > -1) {print "File $filename was transferred successfully to the $path directory\n";return 1;} else {print File transfer of $filename faled\n";return 0; }} # sub
Here's an example that uses Net::FTP to list files from a remote FTP server on a web page, with a link from each file to the URL of the file on the remote site:
#!/usr/local/bin/perl -w
use Net::FTP;
$hostname = 'remotehost.com'; # ftp host
$username = 'anonymous'; # username
$password = 'myname@mydomain.com'; # password
$home = '/pub';
$ftp = Net::FTP->new($hostname); # Net::FTP constructor
$ftp->login($username, $password); # log in w/username and password
$pwd = $ftp->pwd; # get current directory
# Now, output HTML page.
print <<HTML;
Content-type: text/html
<HTML>
<HEAD>
<TITLE>Download Files</TITLE>
</HEAD>
<BODY>
<B>Current working directory:</B> $pwd<BR>
Files to download: <P>
HTML
@entries = $ftp->ls($home); # slurp all entries into an array
foreach (@entries) { # now, output links for all files in the ftp area
# as links
print "<INPUT TYPE=hidden NAME=\"files\" VALUE=\"$_\">\n";
print "<A HREF=\"ftp://$hostname$_\">",
"<IMG SRC=\"http://www/icons/f.gif\" border=0>\n";
print " $_</A><BR>\n";
}
print <<HTML;
</BODY>
</HTML>
HTML
$ftp->quit; # end FTP session
The Net::FTP module implements a subset (as shown earlier in this chapter)
of the FTP protocol as defined in RFC 959. In addition to providing the
methods shown below, the module inherits from Net::Cmd. Some of the Net::FTP
methods return an object derived from the dataconn
class (which is in turn derived from the IO::Socket::INET class), as noted
in the entries for those methods.
The following methods are defined by Net::FTP:
machine name
Specifies a remote machine to which you want to autologin:
Instead ofmachine remotehost.com
machine
name, you can specify the single
word default to match any machine name.
This is usually used for anonymous logins to machines not listed in
.netrc.
login name
If present, identifies
the user who logs in to the remote machine, where
name is the login name.
password passwd
If present, gives the password for the user. The autologin process uses the specified password if the remote server requires one.
account acctpw
If present, gives an additional password for the user. The autologin process uses this password if the remote server requires one.
macdef name
If present, defines a macro with the specified name. Net::Netrc simply parses this field, in order to maintain compatibility with FTP.
Here's an example of a typical .netrc entry:
Entering your username and password for remote sites in unencrypted form has serious security implications. Many sites consider .netrc files a violation of security policy and do not allow them. In addition, most FTP clients require that the .netrc file be owned by you and readable only by you, with permissions set to 0400 or 0600. If the permissions aren't correctly set, the autologin process aborts. Net::Netrc follows this security convention - if the permissions and ownership are not correct, the .netrc file isn't read, and a warning message is issued.machine remotehost.com login username password userpasswd
Net::Netrc implements a simple interface to the .netrc file, telling you which hosts you can automatically connect to. It doesn't actually connect to any remote hosts; it's simply used to query your configuration file and return the value of the tokens.
The following methods are supplied by Net::Netrc:
Presentation itself is junk, only comments have value
| Re: Beginners guide to
Net::FTP by runrig (Monsignor) on Aug 14, 2002 at 17:16 UTC |
by Aristotle (Chancellor) on Aug 14, 2002 at 21:43 UTC |
| Re: Beginners guide to
Net::FTP by jbowshaw (Initiate) on Mar 21, 2008 at 15:24 UTC |
#!/perl/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $URL = 'ftp://ftp.abc.de/pub/anyfile';
my $req = HTTP::Request->new(GET => $URL);
my $contents;
$ua->request($req,
sub {
($contents, undef) = @_;
# the contents of the file is now in $contents
# you can save it to a file, send it via email, and whatnot
});

Here's the first:
#!/usr/bin/perl
use Net::FTP;my $host="aplawrence.com";
my $directory="pub";
$ftp=Net::FTP->new($host,Timeout=>240) or $newerr=1;
push @ERRORS, "Can't ftp to $host: $!\n" if $newerr;
myerr() if $newerr;
print "Connected\n";
$ftp->login("ftp","apl\@") or $newerr=1;
print "Getting file list";
push @ERRORS, "Can't login to $host: $!\n" if $newerr;
$ftp->quit if $newerr;
myerr() if $newerr;
print "Logged in\n";
$ftp->cwd($directory) or $newerr=1;
push @ERRORS, "Can't cd $!\n" if $newerr;
myerr() if $newerr;
$ftp->quit if $newerr;
@files=$ftp->dir or $newerr=1;
push @ERRORS, "Can't get file list $!\n" if $newerr;
myerr() if $newerr;
print "Got file list\n";
foreach(@files) {
print "$_\n";
}
$ftp->quit;
sub myerr {
print "Error: \n";
print @ERRORS;
exit 0;
}
Pretty simple, right? Net::FTP makes it all so easy, so let's do something that would absolutely drive me batty without it.
#!/usr/bin/perl
use Net::FTP;
$date=shift @ARGV;
@months=qw(null Jan Feb Mar Apr My Jun Jul Aug Sep Oct Nov Dec);
@hosts=qw(pcunix.org pcunix.com xyz.com);
@dirs=qw(pub pub pub);
@logins=qw(ftp anonymous fred);
@passwords=qw(tony\@ apl\@ fxdfed);
$x=0;
foreach(@months) {
$months{$_}=$x++;
}
# we need this hash laterif (not $date) {
$now=time();
$now -= (24 * 3600 );
# yesterday
($nowsec,$nowmin,$nowhr,$nowday,$nowmon,$nowyr,$nowdow,$nowdoy,$nowdst)=localtime($now);
$nowyr+=1900;$nowmon++;
$date=sprintf("%.2d/%.2d/%.4d",$nowmon,$nowday,$nowyr);
print "Using $date\n";
}
$now=time();
($nowsec,$nowmin,$nowhr,$nowday,$nowmon,$nowyr,$nowdow,$nowdoy,$nowdst)=localtime($now);
$nowyr+=1900;
# need $nowyr later($month,$day,$year)=split /\//,$date;
#
# broken next century - blame me then
#
$year+=2000 if $year < 100;$x=0;
foreach (@hosts) {
$newerr=0;
$ftp=Net::FTP->new($_,Timeout=>240) or $newerr=1;
push @ERRORS, "Can't ftp to $_: $!\n" if $newerr;
next if $newerr;
print "Connected $_\n";
$ftp->login($logins[$x],$passwords[$x]) or $newerr=1;
push @ERRORS, "Can't login to $_: $!\n" if $newerr;
$ftp->quit if $newerr;
next if $newerr;
print "Logged in $_\n";$ftp->cwd($dirs[$x]) or $newerr=1;
push @ERRORS, "Can't cd $dirs[$x] on $_ $!\n" if $newerr;
$ftp->quit if $newerr;
next if $newerr;
print "Getting file list $_\n";
@files=$ftp->dir or $newerr=1;
push @ERRORS, "Can't get file list on $_ $!\n" if $newerr;
$ftp->quit if $newerr;
next if $newerr;
print "Got list $_\n";print "Looking for $date $time\n";
foreach(@files) {
$_=substr($_,41);
s/ */ /g;
s/^ *//g;
chomp;
@stuff=split / /;
# if it's today, the year slot will have time instead
# so make it this year
$stuff[2]=$nowyr if /:/;$ftp->quit if ($stuff[2] < $year);
next if ($stuff[2] < $year);
$ftp->quit if ($months{$stuff[0]} < $month and $stuff[2] == $year);
next if ($months{$stuff[0]} < $month and $stuff[2] == $year);
$ftp->quit if ($stuff[0] < $day and $stuff[2] == $year and $months{$stuff[0]} == $month);
next if ($stuff[1] < $day and $stuff[2] == $year and $months{$stuff[0]} == $month);print "Getting $_\n";
$ftp->get($stuff[3],$stuff[3]) or $newerr=1;
push @ERRORS, "Couldn't get $stuff[3] $!\n" if $newerr;
}$ftp->quit;
}print @ERRORS;
exit 0;
Perl Net--FTP aplawrence.com/Unixart/perlnetftp.html
Beginners guide to NetFTP presendtaion is very weak, but some comments are insightful
Copyright © 1996-2009 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
Disclaimer:
Last modified: October 10, 2009