Wednesday, March 23, 2016

Automating copying SSH keys to multiple servers in a cluster

Lets make a system for configuring the /etc/hosts and ssh keys on the servers

1. Make the ssh key
http://stackoverflow.com/questions/2848725/how-can-i-ssh-inside-a-perl-script


2. Read a list of pairs of ip addresses and host names from a CSV file.

hosts.csv
192.168.0.100,centos0
192.168.0.101,centos1
192.168.0.102,centos2
192.168.0.103,centos3
192.168.0.104,centos4

Under construction

Add current working directory to @INC to load the modules that we will create below

http://www.perlmonks.org/?node_id=375341  
use lib '.';
 
From: http://www.tutorialspoint.com/perl/perl_oo_perl.htm

#!/usr/bin/perl

package ServerInfo;

sub new
{
    my $class = shift;
    my $self = {
        _hostName  => shift,
        _ipAddress => shift,
        _password  => shift,

    };
# Print all the values just for clarification.
    print "hostName is $self->{_hostName}\n";
    print "ipAddress is $self->{_ipAddress}\n";
    bless $self, $class;
    return $self;
}

sub getHostName {
    my( $self ) = @_;
    return $self->{_hostName};
}

sub getIpAddress {
    my( $self ) = @_;
    return $self->{_ipAddress};
}

sub getPassword {
    my( $self ) = @_;
    return $self->{_password};
}

1;




Now create Person object in the config.pl file as follows:

#!/usr/bin/perl

use ServerInfo;

if ($#ARGV != 0) {
   print("Args: ");
   exit;
}

$passWord = $ARGV[0];

$object = new ServerInfo( "192.168.0.100", "centos0",$passWord);

$hostName = $object-> getHostName();
print "HostName is : $hostName\n";

$ipAddress = $object-> getIpAddress();
print "ipAddress is : $ipAddress\n";


Import the host file.

#!/usr/bin/perl

#!/usr/bin/perl use strict; use warnings;   use Text::CSV; my $csv = Text::CSV->new({ sep_char => ',' });   my $file = $ARGV[0] or die "Need to get CSV file on the command line\n";   my $sum = 0; open(my $data, '<', $file) or die "Could not open '$file' $!\n"; while (my $line = <$data>) { chomp $line;   if ($csv->parse($line)) {   my @fields = $csv->fields(); $sum += $fields[2];   } else { warn "Line could not be parsed: $line\n"; } } print "$sum\n";



3. Add the new hosts information to the /etc/hosts file




4. Add the generated ssh key to the remote servers



cat ~/.ssh/id_rsa.pub | ssh root@HOST "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized
 
chmod 700 ~/.ssh

chmod 600 ~/.ssh/authorized_keys 
 
#Restart sshd on the remote host
 
sudo /etc/init.d/sshd restart < $password
 
Now test the passwordless ssh login to root@host 


5. Test the ssh passwordless login to the remote servers