18.2. Being an FTP ClientProblemYou want to connect to an FTP server and get or put files. You might want to automate the one-time transfer of many files or automatically mirror an entire section of an FTP server, for example. SolutionUse the CPAN module Net::FTP: use Net::FTP; $ftp = Net::FTP->new("ftp.host.com") or die "Can't connect: $@\n"; $ftp->login($username, $password) or die "Couldn't login\n"; $ftp->cwd($directory) or die "Couldn't change directory\n"; $ftp->get($filename) or die "Couldn't get $filename\n"; $ftp->put($filename) or die "Couldn't put $filename\n"; Discussion
Using the Net::FTP module is a three-part process:
connect
to a server, identify and
authenticate
yourself, and
transfer
files. All interaction with the FTP server happens through method calls on a Net::FTP object. If an error occurs, methods return
The connection is established with the $ftp = Net::FTP->new("ftp.host.com", Timeout => 30, Debug => 1) or die "Can't connect: $@\n";
The
Having connected, the next step is to authenticate. Normally, you'll want to call
$ftp->
If you call
Once authenticated, the usual FTP commands are available as methods called on your Net::FTP object. The $ftp->put($localfile, $remotefile) or die "Can't send $localfile: $!\n"; If you omit the second argument, the remote file will have the same name as the local file. You can also send from a filehandle (in which case the remote filename must be given as the second argument): $ftp->put(*STDIN, $remotefile) or die "Can't send from STDIN: $!\n";
If the transfer is interrupted, the remote file is not automatically deleted. The
To fetch a file, use the $ftp->get($remotefile, $localfile) or die "Can't fetch $remotefile : $!\n";
You can also $ftp->get($remotefile, *STDOUT) or die "Can't fetch $remotefile: $!\n";
Pass
The
Use $ftp->cwd("/pub/perl/CPAN/images/g-rated"); print "I'm in the directory ", $ftp->pwd(), "\n";
$ftp->mkdir("/pub/gnat/perl", 1) or die "Can't create /pub/gnat/perl recursively: $!\n";
If
The @lines = $ftp->ls("/pub/gnat/perl") or die "Can't get a list of files in /pub/gnat/perl: $!"; $ref_to_lines = $ftp->dir("/pub/perl/CPAN/src/latest.tar.gz") or die "Can't check status of latest.tar.gz: $!\n";
When you're done and want to close up gracefully, use the $ftp->quit() or warn "Couldn't quit. Oh well.\n"; Other methods rename, change ownership and permissions of remote files, check the size of the remote file, and so on. Read the Net::FTP documentation for details. If you want to mirror files between machines, use the excellent mirror program written in Perl by Lee McLoughlin. Look for it on the Web at http://sunsite.doc.ic.ac.uk/packages/mirror/. See AlsoYour system's ftp (1) and ftpd (8) manpages (if you have them); the documentation for the Net::FTP module from CPAN Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|