Friday, December 2, 2011

SFTP/SCP autologin Perl script

I have wrote script to autologin scp and transfer specified file. I am using perl Net::SCP::Expect module for it.

Requirement:   Net::SCP::Expect  perl module is required for script.
 
Install required module:

perl -MCPAN -e 'install Net::SCP::Expect' 

Script name is autossh.pl


-----------------------START--------------------------

#!/usr/bin/perl -w

use strict;
use Net::SCP::Expect;

if ($#ARGV != 0 ) {
print "usage: autossh.pl \n";
exit;
}

my $server=$ARGV[0];

my $user = "orion";
my $password = 'mypassword';
my $remotedir = "/home/local/mydata/";
my $filelocation = "/home/remote/backup/";

print "Login...Starting scp...";
my $scpe = Net::SCP::Expect->new(host=>$server, user=>$user, password=>$password, recursive=>'1', auto_yes => '1', auto_quote => '0');

print "\nFILELOCATION:" . $filelocation . "*\n";
print "REMOTEDIR: " . $remotedir . "\n";

$scpe->scp($filelocation, $remotedir);

print "SCP complete\n";

-----------------------END--------------------------

To run script type.

#./autossh.pl servername.com

This script will copy /home/mydata local directory to remove server "remoteserver.com" at /home/remote/backup directory.

5 comments:

  1. I am new to perl and was looking for a solution from non-interactive scp and your solution looked promising.

    I created the above script as kfstscp.pl and run the script it fails with the below error.can you please help

    Can't locate Net/SCP/Expect.pm in @INC (@INC contains: /usr/perl5/5.8.4/lib/sun4-solaris-64int /usr/perl5/5.8.4/lib /usr/perl5/site_perl/5.8.4/sun4-solaris-64int /usr/perl5/site_perl/5.8.4 /usr/perl5/site_perl /usr/perl5/vendor_perl/5.8.4/sun4-solaris-64int /usr/perl5/vendor_perl/5.8.4 /usr/perl5/vendor_perl .) at ./kfstscp.pl line 4.
    BEGIN failed--compilation aborted at ./kfstscp.pl line 4.

    ReplyDelete
  2. You need to install Net::scp::expect perl module. You can use cpan shell to install it. Just google it how to.

    ReplyDelete
  3. Anyway I have updated document, how to install Net::scp::Expect module. Enjoy!!

    ReplyDelete
  4. In Windows 7 I tried this in cmd perl -MCPAN -e 'install Net::SCP::Expect' it install but still in eclipse its throwing same error and perldoc doesnot show any documentation for Net::SCP::Expect after installing.

    ReplyDelete