Monday, May 30, 2016

Net::SFTP::Foreign - FTP protocol to get files from folder or file from remote server.

#!/usr/bin/perl
use Switch;
use Getopt::Long;
use Net::SFTP::Foreign;

#./sftp_get.pl -h hello.domainname.com -u root -p root123 -s "folder" -f "/usr/local/nagios/libexec/tools/linux/" -t "/usr/local/nagios/libexec/tools/linux/"
#./sftp_get.pl -h hello.domainname.com -u root -p root123 -s "file" -f "/usr/local/nagios/libexec/tools/linux/ran.txt" -t "/usr/local/nagios/libexec/tools/linux/ran.txt"

my $status = GetOptions(
        "host|h=s" => \$host,
        "username|u=s"  => \$username,
        "password|p=s"   => \$password,
        "from_dir|f=s"  => \$FROM_DIR,
        "to_dir|t=s"    => \$TO_DIR,
        "switch|s=s"    => \$fcopy,
);

if ( $status == 0 ) {
        print_usage();
        exit(3);
}

my $sftp;
$sftp = Net::SFTP::Foreign->new (
    $host,
    timeout         => 240,
    user            => $username,
    password        => $password,
    autodie         => 1,

);
switch ($fcopy)
{
case "folder"
{

$sftp->die_on_error("Unable to establish SFTP connection");
my $rlist = $sftp->ls("$TO_DIR",no_wanted => qr/^\./);
for (@$rlist)
{
#print "$_->{filename}\n";
my $FROM_FILE=$FROM_DIR.$_->{filename};
my $TO_FILE=$TO_DIR.$_->{filename};
#printf "From Files:$FROM_FILE \n";
#printf "To Files:$TO_FILE\n";
$sftp->get("$FROM_FILE","$TO_FILE");
}
if($sftp->status)
{
print "Unsuccessfull filecopy copy to destination\n";
}
}

case "file"
{
$sftp->get("$FROM_DIR","$TO_DIR");
}

else {printf "check the option properly\n"}

}

$sftp->disconnect;
closedir(DIR);



sub print_usage {
        print <Usage: sftp_get.pl -H host -u username -p password -s "file|folder" -f "from path" -t "to path"
Options:

    -H --host IPADDRESS
        Check interface on the indicated host.
    -u --username
        Provided the user name for the remote SFTP server, which has a privilage to read/write files
    -p --password
        Password for the remote SFTP server
    -f --from
       copy file/files from the location depending on the switch used
    -t --to
        put the file/files in this location depending on the switch used
    -s --switch
        it can be either one of file ot folder
EOU
}


No comments:

Post a Comment