The Perl and Raku Conference 2025: Greenville, South Carolina - June 27-29 Learn more

#!/usr/bin/env perl
use strict;
use lib 'lib';
use File::Temp qw/ :POSIX /;
sub help ($);
if (!@ARGV) {
warn "No argument specified.\n\n";
help(1);
}
my $list_hosts_only = 0;
my ($user, $port, $timeout, $verbose);
my (@exprs);
my $concurrency = 20;
my $fetch_value;
for (@ARGV) {
if (defined $fetch_value) {
$fetch_value->($_);
undef $fetch_value;
next;
}
if (/^-([A-Za-z])(.*)/) {
if ($2 ne '') {
die "Unknown option: $_\n";
}
my $group = $1;
if ($group eq 'l') {
$list_hosts_only = 1;
} elsif ($group eq 'u') {
$fetch_value = sub { $user = shift };
} elsif ($group eq 't') {
$fetch_value = sub { $timeout = shift };
} elsif ($group eq 'h') {
help(0);
} elsif ($group eq 'p') {
$fetch_value = sub { $port = shift };
} elsif ($group eq 'v') {
$verbose = 1;
} elsif ($group eq 'c') {
$fetch_value = sub { $concurrency = shift };
} else {
die "Unknown option: $_\n";
}
next;
}
push @exprs, $_;
}
if (!@exprs) {
die "No cluster expression specified.\n";
}
my $expr = join ' ', @exprs;
if ($verbose) {
warn "Cluster expression: $expr\n";
}
my $home = File::HomeDir->my_home;
if (!defined $home) {
die "Can't find the home for the current user.\n";
}
my $pubkey_file = "$home/.ssh/id_rsa.pub";
if (-f $pubkey_file) {
if ($verbose) {
warn "Found public key file $pubkey_file.\n";
}
} else {
my $cmd = "(echo; echo y; echo; echo) | ssh-keygen -q -t rsa";
if ($verbose) {
warn "Running command [$cmd]...\n";
}
if (system($cmd) != 0) {
die "Generating SSH key failed.\n";
}
}
open my $in, $pubkey_file or
die "Can't open $pubkey_file for reading: $!\n";
my $pubkey = do { local $/; <$in> };
close $in;
my ($rc, $rcfile) = SSH::Batch::ForNodes::init();
SSH::Batch::ForNodes::load_rc($rc, $rcfile);
my $set = SSH::Batch::ForNodes::parse_expr($expr);
if ($set->is_empty) {
die "No machine to be operated.\n";
}
my @hosts = sort $set->elements;
if ($verbose) {
warn "Cluster set: @hosts\n";
} elsif ($list_hosts_only) {
print "Cluster set: @hosts\n";
}
if ($list_hosts_only) {
exit(0);
}
my $password;
print STDERR "Password:";
ReadMode(2);
while (not defined ($password = ReadLine(0))) {
}
ReadMode(0);
chomp $password;
if (!$password) {
die "No password specified.\n";
}
my (%conns, @pids, @outs);
my %pid2host;
my $active_count = 0;
while (1) {
last if !@hosts && !@pids;
my @active_hosts;
while ($active_count < $concurrency) {
last if !@hosts;
my $host = shift @hosts;
$active_count++;
$conns{$host} = Net::OpenSSH->new(
$host,
async => 1,
defined $timeout ? (timeout => $timeout) : (),
defined $user ? (user => $user) : (),
defined $port ? (port => $port) : (),
password => $password,
);
push @active_hosts, $host;
}
for my $host (@active_hosts) {
my ($out, $outfile) = tmpnam();
push @outs, $outfile;
my $pid = $conns{$host}->system({
stdin_data => $pubkey,
stdout_fh => $out,
stderr_to_stdout => 1,
async => 1,
#tty => 1,
}, 'if [ ! -d ~/.ssh ]; then mkdir ~/.ssh; fi; chmod 700 ~/.ssh; cat >> ~/.ssh/authorized_keys && chmod 640 ~/.ssh/authorized_keys');
push @pids, $pid;
$pid2host{$pid} = $host;
}
## HERE...
if (@pids) {
my $pid = shift @pids;
my $host = delete $pid2host{$pid};
$active_count--;
print "===" x 10, " $host ", "===" x 10, "\n";
if (!defined $pid) {
warn "Failed to connect to host $host.\n";
delete $conns{$host};
next;
}
my $exit = 0;
my $ret = waitpid($pid, 0);
if ($ret > 0) {
$exit = ($? >> 8);
} else {
#redo if ($! == EINTR);
warn "$host: waitpid($pid) failed: $!\n";
delete $conns{$host};
next;
}
delete $conns{$host};
my $outfile = shift @outs;
my $in;
if (!open $in, $outfile) {
warn "Can't open $outfile for reading: $!\n";
next;
}
while (<$in>) {
print;
}
if ($exit > 0) {
warn "Remote command returns status code $exit.\n";
}
print "\n";
close $in;
}
}
sub help ($) {
my $exit_code = shift;
my $msg = <<'_EOC_';
USAGE:
key2nodes [OPTIONS] HOST_PATTERN... [OPTIONS]
OPTIONS:
-c <num> Set SSH concurrency limit. (default: 20)
-h Print this help.
-l List the hosts and do nothing else.
-p <port> Port for the remote SSH service.
-t <timeout> Specify timeout for net traffic.
-u <user> User account for SSH login.
-v Be verbose.
_EOC_
if ($exit_code == 0) {
print $msg;
exit(0);
} else {
warn $msg;
exit($exit_code);
}
}
__END__
=head1 NAME
key2nodes - Push SSH public keys to remote clusters
=head1 SYNOPSIS
# run a command on the specified servers:
$ key2nodes 'ws[1101-1105].as.com'
=head1 USAGE
key2nodes [OPTIONS] HOST_PATTERN... [OPTIONS]
=head1 OPTIONS
-c <num> Set SSH concurrency limit. (default: 20)
-h Print this help.
-l List the hosts and do nothing else.
-p <port> Port for the remote SSH service.
-t <timeout> Specify timeout for net traffic.
-u <user> User account for SSH login.
-v Be verbose.
=head1 DESCRIPTION
This script push local ~/.ssh/id_rsa.pub file (i.e. the SSH public key) onto the remote server's ~/.ssh/authorized_keys. It will chmod .ssh to 700 and .ssh/authorized_keys to 640.
If there's no .ssh directory on the remote server, it will try to create one.
Note that the sh/bash shell is assumed on the remote machines.
When no ~/.ssh/id_rsa.pub file found on the local machine, it will invoke "ssh-keygen -t rsa" automatically.
=head1 SEE ALSO
L<fornodes>, L<atnodes>, L<tonodes>, L<SSH::Batch>, L<Net::OpenSSH>.
=head1 COPYRIGHT AND LICENSE
This module as well as its programs are licensed under the BSD License.
Copyright (c) 2009, Yahoo! China EEEE Works, Alibaba Inc. All rights reserved.
Copyright (C) 2009, Agent Zhang (agentzh). All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
=over
=item *
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
=item *
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
=item *
Neither the name of the Yahoo! China EEEE Works, Alibaba Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
=back
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.