Skip to content

Instantly share code, notes, and snippets.

@UKNC
Last active April 29, 2017 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UKNC/19b8f380a82a0e9ba41f679cbfe543ed to your computer and use it in GitHub Desktop.
Save UKNC/19b8f380a82a0e9ba41f679cbfe543ed to your computer and use it in GitHub Desktop.
Automate ssh-copy-id
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
my $pwdfile;
GetOptions( "file=s" => \$pwdfile ) or die "Error in cmd args";
if ( !$pwdfile ) {
print qq{
Usage:
$0 --file=passwords.txt
passwords.txt has the following format:
host1 password1
host2 password2
...
hostN passwordN
};
exit;
}
print "Using password file: $pwdfile\n";
open my $fh, "<", $pwdfile or die "Cannot open $pwdfile: $!";
my $lineCnt = 0;
while ( my $line = <$fh> ) {
$lineCnt++;
chop $line;
my $spaceNum = () = $line =~ /\s+/g;
if ( $spaceNum > 1 ) {
print "$lineCnt: more than two spaces, skipping line: $line\n";
next;
}
my ($host, $pwd) = split / /, $line;
my $cmd = "sshpass -p $pwd ssh-copy-id root\@$host -o StrictHostKeyChecking=no";
my $out = `$cmd`;
print "$cmd\n$out\n\n";
}
close $fh;
@UKNC
Copy link
Author

UKNC commented Apr 29, 2017

If you have many servers which should be updated with your key through "ssh-copy-id root@host", this perl script with sshpass allow to automate the task.
Put host password pairs into passwd.txt, e.g.

myhost1 Ksiswmsw83
myhost2 ss3trefefrf@34
myhost3 768jdw2ewd

and run

@>> ./masscopyid.pl -file=passwd.txt

This command will execute sshpass for each host password tuple.

NOTES

  1. Passwords cannot have spaces.
  2. Don't forget to remove passwd.txt after usage!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment