This script looks for files in an incoming directory and transfers them to a remote server via openssh's sftp. The authentication is handled via public key authentication.


#!/usr/bin/perl

use File::stat qw(:FIELDS);
use File::Copy;

$INCOMING = '/u20/home/project99/incoming';
$ARCHIVE  = '/u20/home/project99/archive';
$Log =  '/u20/home/project99/logs/project99-xfer.log';
$TMP = '/u20/home/project99/tmp';
$SYNIVERSE = '10.250.1.2';
$USER = 'some-user';

$admin = 'admin@mycompany.com';

$debug = 0;

opendir INCOMING,"$INCOMING";
@incoming = readdir INCOMING; 
closedir(INCOMING);


foreach $file (@incoming) {
	next if ( ($file eq '.') or  ($file eq '..') );
	$stat = GetFileStats("$INCOMING/$file");
	$age = time - $stat->{ctime};
	WriteLog($Log,"Found $file - age=$age") if ($debug > 0);
	if ($age > 120) {
		$status = SendFile("$INCOMING/$file","$file");
		WriteLog($Log,"$file - $status");
		if ($status eq 'fail') {
			Fail("Failed transfering a project99 file. See $Log on xfer3 for details.");
		} else {
			move("$INCOMING/$file","$ARCHIVE/$file");
		}
	} else {
		WriteLog($Log,"Receiving $file");
	}
}


sub Fail {
	my $message = shift;
	WriteLog($Log,"ERROR - $message");
        $Result = "SENT";
        open(OUT, "|/usr/bin/mailx -s \'project99 xfer failed on xfer3\' $admin") or $Result = 'FAILED';
        if ($Result eq 'SENT') {
                 print OUT "$message";
        }
        close(OUT);
	WriteLog($Log,"Failed to send mail") if  ($Result eq 'FAILED');
}


sub SendFile {
        my ($scp);
        my $xfer = "fail";
        my $file = shift;
        my $filename = shift;
	WriteLog($Log,"Begin transfer for $file");
	my @sftp = `/usr/local/bin/sftp -vb /dev/fd/0 $USER\@$SYNIVERSE  2>\&1 < $st_size,
                                atime  => $st_atime,
                                mtime  => $st_mtime,
                                ctime  => $st_ctime,
                                );
        return \%Stats;
}

sub WriteLog {
        my ($Log,$Entry) = @_;
        my $time=localtime(time);
	my $MaxLogFileSize = "100000";
        if (-e "$Log") {
                my $FileSize = -s "$Log";
                RollLog($Log) if ($FileSize > $MaxLogFileSize);
        }
        open (LOG, ">>$Log") or die "Failed opening Log $Log($!)";
        print LOG "$time - $Entry\n";
        close (LOG);
}
#
sub RollLog {
        my $Log = shift;
        my $Log1 = $Log . '.1';
        my $Log2 = $Log . '.2';
        my $Log3 = $Log . '.3';
        move("$Log2", "$Log3")if (-e "$Log2");
        move("$Log1", "$Log2")if (-e "$Log1");
        move("$Log", "$Log1");
}
#






You are visitor number 762