Perl transfer files using ssh (shortcut command)

transfer.pl

#!/usr/bin/perl

use Term::ANSIColor;

if (! defined $ARGV[0]) {
 print "Don't be stupid please...";
 exit 0;
}

my $file = "/home/user/hosts.txt";
my $keysdir = "/home/user/keys";
my $username = $ARGV[1];
my $remote_hostname = $ARGV[0];
my $xfer = $ARGV[2];
my $time = qx/date/;

if ( $ARGV[0] =~ /edit/) {
 my $command = "vim $file";
 system ($command);
 exit 0;
}

if ( $ARGV[0] =~ /list/) {
 print "\n";
 open (my $data, "<" , "$file")
 or die "Failed to open file: $!\n";
 while (my $row = <$data>) {
 chomp $row;
 print "$row\n"
 }
 exit 0;
}

if (! defined $ARGV[2]) {
 print "Please load a file!";
 exit 0;
}

open (my $data, "<" , "$file")
or die "Failed to open file: $!\n";

while (my $row = <$data>) {
 chomp $row;
 if ( $row =~ /$remote_hostname/) {
 if ( defined $ARGV[3] ) {
 my @args = ($row, $ARGV[3]);
 ssh_transfer_key(@args);
 exit 0;
 }
 else {
 ssh_transfer($row);
 exit 0;
 }
 }
}

print "Remote host not found!";

sub ssh_transfer() {

 my $row = $_[0];
 my @parts = split(",",$row);
 my $hostname = $parts[0];
 my $ipaddress = $parts[1];
 my $port = $parts[2];
 print $time;
 print "Transfering file to $hostname ...\n";
 print color("red"), "scp -P $port $xfer $username@$ipaddress:/tmp \n", color("reset");
 my $command = "scp -P $port $xfer $username"."@"."$ipaddress:/tmp/";
 system($command);
 exit 0;

}

sub ssh_transfer_key() {

 my $row = $_[0];
 my $key = $_[1];
 my @parts = split(",",$row);
 my $hostname = $parts[0];
 my $ipaddress = $parts[1];
 my $port = $parts[2];
 print $time;
 print "Transfering file to $hostname ...\n";
 print color("red"), "scp -i $keysdir/$key -P $port $xfer $username"."@"."$ipaddress:/tmp \n", color("reset");
 my $command = "scp -i $keysdir/$key -P $port $xfer $username"."@"."$ipaddress:/tmp/";
 system($command);
 exit 0;

}

close $data;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s