Friday, March 29, 2013

Perl script for sftp server transaction check

Need to do sftp server transaction check such as upload/download a test file?

Here's the script for that. You can also download it here

#!/usr/bin/perl

use Net::SFTP;
use Try::Tiny;

$SCRIPT_NAME="check_sftp";
$SCRIPT_PATH="/tmp/check_sftp";

$local_dir=$SCRIPT_PATH;

$SSH_KEY_FILE=$local_dir."/id_rsa";


#----------------------------------------------------------------------------
# Validate Arguments
#----------------------------------------------------------------------------
if($ARGV[0] eq "" || $ARGV[1] eq "" || $ARGV[2] eq "")
{
print "usage: ./$SCRIPT_NAME.pl server_name user_name sftp_directory\n";
exit;
}

$SERVER_NAME=$ARGV[0];
$USER_NAME=$ARGV[1];
$sftp_dir=$ARGV[2];

#crreate the test file
$test_str=`date +"%m-%d-%Y_%H:%M"`;
chomp($test_str);
$test_file=$SERVER_NAME."_test.txt";

$local_test_file=$local_dir."/".$test_file;
$sftp_test_file=$sftp_dir."/".$test_file;

$command="echo $test_str > $local_test_file";
system($command);


#set sftp connecton detail
%sftp_args=( user => "$USER_NAME", ssh_args => {identity_files => ["$SSH_KEY_FILE"]} );
$sftp_args{warn}=false;
#$sftp_args{debug} = 1;

try
{
$sftp=Net::SFTP->new($SERVER_NAME, %sftp_args) or die "Cannot connect to $SERVER_NAME";


#upload file
undef $staus;
$status=$sftp->put($local_test_file,$sftp_test_file);
if(!defined($status))
{
print "Cannot upload file to $SERVER_NAME";
exit;
}

#remove local test file
$command="rm $local_test_file";
system($command);

#download the test file
undef $staus;
$status=$sftp->get($sftp_test_file,$local_test_file);
if(!defined($status))
{
print "Cannot download file from $SERVER_NAME";
exit;
}

#check to make sure the test file got downloaded from the sftp
$result=`ls $local_test_file`;
chomp($result);
if($result ne $local_test_file)
{
print "Cannot upload/download file from $SERVER_NAME";
exit;
}

   
    #make sure the file got downloaded correctly and contain the correct string
    open(READ_FILE,$local_test_file);
        $str=<READ_FILE>;
    chomp($str);
        if($str eq $test_str)
        {
        print "Success";
        }
        else
        {
        print "Cannot upload/download file from $SERVER_NAME";
        }
        close(READ_FILE);

#remove local test file
$command="rm $local_test_file";
system($command);

}
catch
{
print "Cannot connect to $SERVER_NAME";
exit;
};