Automating SSH public key pushes with Perl

| 0 Comments

Automating SSH public key pushes to servers.

The code below uses Expect and SSH to create & permission the .ssh directory. Followed by SSH copying the local temp file as the authorized_keys file to the .ssh subdir on the target server .

Be sure to set StrictHostKeyChecking=no in the SSH client side config.

---

#!/usr/bin/perl

use strict;
use warnings;
use English;
use Expect;
use Net::Ping;
my $username = "USER";
my $password = "PASS";
my $homedir  = "\/export\/home\/$username";
my $ssh_dir  = "$homedir\/.ssh";
my $ssh_pub  = "
ssh-dss BLAH BLAH use your own public key file entry here.
";

if ( ! $ARGV[0] ) {
        print "$0  \n";
        exit
} 

my $host = "$ARGV[0]";
my $p 	 = Net::Ping->new();
if ( $p->ping($host) ) {
	print "Deploying public key to $host \n";
	create_ssh_dir();
	chmod_ssh_dir();
	push_ssh_key();
} else {
	print "Seems $host is not reachable \n";
}
$p->close();

sub create_ssh_dir {
my $ssh_cmd  = "/usr/bin/ssh $username\@$host 'mkdir $ssh_dir'";

my $timeout  = '5';
my $exp      = Expect->spawn($ssh_cmd) or die "Cannot spawn ssh command \n";
$exp->expect($timeout, ["Password:"]);
$exp->send("$password\n");
$exp->soft_close();
}

sub chmod_ssh_dir {
my $ssh_cmd  = "/usr/bin/ssh $username\@$host 'chmod 755 $ssh_dir'";

my $timeout  = '5';
my $exp      = Expect->spawn($ssh_cmd) or die "Cannot spawn ssh command \n";
$exp->expect($timeout, ["Password:"]);
$exp->send("$password\n");
$exp->soft_close();
}

sub push_ssh_key {
my $tmp_file  = "/tmp/authorized_keys.$$";
chomp $ssh_pub;

open  ( AUTHKEY, ">$tmp_file") || die ("Unable to create $tmp_file\n");
print AUTHKEY "$ssh_pub" . "\n";
close ( AUTHKEY );

my $scp_cmd  = "/usr/bin/scp $tmp_file $username\@$host:$ssh_dir/authorized_keys";

my $timeout = '5';
my $exp = Expect->spawn($scp_cmd) or die "Cannot spawn scp command \n";
$exp->expect($timeout, ["Password:"]);
$exp->send("$password\n");
$exp->soft_close();

unlink("$tmp_file");
}

Leave a comment

Recent Entries

Ping Success or Failure using Bash
#!/bin/bash if ping -c 1 hostfoo > /dev/null then echo "ping success" else echo "could not ping hostfoo. exiting..."…
Automating SSH public key pushes with Perl
Automating SSH public key pushes to servers. The code below uses Expect and SSH to create & permission the .ssh…
Write Chinese Characters using Trackpad on Mac
From http://www.apple.com/macosx/refinements Innovative Chinese character input. Until Snow Leopard, if you wanted to enter Chinese characters on a computer, you…