Thursday, July 29, 2004

Perl FTP

Here is the first program I'm giving the source for, it's a FTP upload script that is designed to run from Cron.

use Net::FTP;
use File::Copy;
#Setup the variables
$ftphost = "";
$username = "user";
$password = "password";
$remotedirectory = "public_html";
$outputdirectory = "~/transfered/";
$localdirectory = "~/dropbox/";
$fromaddress = "username\";
$toaddress = "tousername\";
$subject = "Automated FTP Transfer";
# Build the filelist
@files=`ls -1 $localdirectory`;

#Connect to the FTP Server
$ftp = Net::FTP->new("$ftphost", Timeout => 30, Debug => 1) or $erroroutput = $erroroutput."Can't connect: $@\n";

#Login with the username and password
$ftp->login($username, $password) or $erroroutput = $erroroutput."Couldn't authenticate, even with explicit username and password.\n";

#Set Binary Mode

#Change Directories
$ftp->cwd($remotedirectory) or $erroroutput = $erroroutput."Couldn't change directory\n";

#Upload the files if everything is OK So far.
if (!$erroroutput){
foreach $file (@files) {
chomp $file;
$ftp->put ($localdirectory.$file) or $erroroutput = $erroroutput."couldn't upload $file\n";

#Close the FTP Connection

#Mail the results
$mailer = "/usr/lib/sendmail -f$fromaddress -oi";
open(MAIL, "|$mailer -t") || die;
print MAIL "To: $toaddress\n";
print MAIL "Subject: $subject\n\n";
if ($erroroutput) {
print MAIL "Error $erroroutput";
foreach $file (@files) {
print MAIL "Did not transfer $file\n";
else {
foreach $file (@files) {
chomp $file;
print MAIL "Transferred $file\n";
move ("$localdirectory$file", "$outputdirectory$file");
close (MAIL);

No comments: