/
atnodes
executable file
·459 lines (381 loc) · 13.4 KB
/
atnodes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
#!/usr/bin/env perl
use strict;
use warnings;
#use Smart::Comments::JSON '##';
use lib 'lib';
use Net::OpenSSH;
use Term::ReadKey;
use SSH::Batch::ForNodes;
use File::Temp qw/ :POSIX /;
use Time::HiRes qw/sleep/;
sub help ($);
sub check_openssh_version ($);
if (!@ARGV) {
warn "No argument specified.\n\n";
help(1);
}
my $list_hosts_only = 0;
my ($user, $port, $timeout, $verbose, $ask_for_pass, $ask_for_passphrase);
my $concurrency = 20;
my (@cmd, @exprs, $ssh_cmd);
$ssh_cmd = $ENV{SSH_BATCH_SSH_CMD};
my $fetch_value;
my $found_sep;
my $last_option;
my $use_tty;
my $line_mode = $ENV{SSH_BATCH_LINE_MODE};
for (@ARGV) {
if (defined $fetch_value) {
$fetch_value->($_);
undef $fetch_value;
next;
}
if ($_ eq '--') {
@cmd = @exprs;
@exprs = ();
$found_sep = 1;
next;
}
if (/^-(.*)/) {
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 'w') {
$ask_for_pass = 1;
} elsif ($group eq 'P') {
$ask_for_passphrase = 1;
} elsif ($group eq 'c') {
$fetch_value = sub { $concurrency = shift };
} elsif ($group eq 'ssh') {
$fetch_value = sub { $ssh_cmd = shift };
} elsif ($group eq 'L') {
$line_mode = 1;
} elsif ($group eq 'tty') {
$use_tty = 1;
} else {
die "Unknown option: $_\n";
}
$last_option = $_;
next;
}
push @exprs, $_;
}
if (defined $fetch_value) {
die "ERROR: Option $last_option takes a value.\n";
}
if (!$found_sep && !@cmd) {
push @cmd, shift @exprs;
}
if (!@cmd) {
die "No command specified.\n";
}
if ($verbose) {
warn "Command: ", (map { "[$_]" } @cmd), "\n";
if (defined $ssh_cmd) {
warn "Using SSH program [$ssh_cmd].\n";
}
}
check_openssh_version($ssh_cmd || 'ssh');
if ($use_tty) {
$concurrency = 1;
}
if (!@exprs) {
die "No cluster expression specified.\n";
}
my $expr = join ' ', @exprs;
if ($verbose) {
warn "Cluster expression: $expr\n";
}
SSH::Batch::ForNodes::init_rc();
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 ($passphrase, $password);
if ($ask_for_passphrase) {
$passphrase = $ENV{SSH_BATCH_PASSPHRASE};
if (!$passphrase) {
print STDERR "Passphrase:";
ReadMode(2);
while (not defined ($passphrase = ReadLine(0))) {
}
ReadMode(0);
print "\n";
chomp $passphrase;
}
if (!$passphrase) {
die "No passphrase specified.\n";
}
} elsif ($ask_for_pass) {
$password = $ENV{SSH_BATCH_PASSWORD};
if (!$password) {
print STDERR "Password:";
ReadMode(2);
while (not defined ($password = ReadLine(0))) {
}
ReadMode(0);
print "\n";
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;
my $ssh = Net::OpenSSH->new(
$host,
async => 1,
defined $timeout ? (timeout => $timeout) : (),
defined $user ? (user => $user) : (),
defined $port ? (port => $port) : (),
defined $passphrase ? (passphrase => $passphrase) : (),
defined $password ? (password => $password) : (),
defined $ssh_cmd ? (ssh_cmd => $ssh_cmd) : (),
);
if ($ssh->error) {
if ($line_mode) {
print STDERR "$host: ";
} else {
print "===" x 7, " $host ", "===" x 7, "\n";
}
warn "ERROR: Failed to establish SSH connection: ",
$ssh->error, "\n";
next;
}
$conns{$host} = $ssh;
$active_count++;
push @active_hosts, $host;
}
for my $host (@active_hosts) {
my ($out, $outfile) = tmpnam();
my $ssh = $conns{$host};
my $pid = $ssh->system({
(defined $password?
(stdin_data => "$password\n") : ()),
stdout_fh => $out,
stderr_to_stdout => 1,
async => 1,
defined $use_tty ? (tty => 1) : (),
}, @cmd);
#warn "PID: $pid\n";
if (!defined $pid or $pid == -1) {
$active_count--;
if ($line_mode) {
print STDERR "$host: ";
} else {
print "===" x 7, " $host ", "===" x 7, "\n";
}
if ($ssh->error) {
warn "ERROR: ", $ssh->error, "\n";
} else {
warn "ERROR: Failed to spawn command.\n";
}
close $out;
unlink $outfile;
delete $conns{$host};
next;
}
push @outs, $outfile;
push @pids, $pid;
$pid2host{$pid} = $host;
}
if (@pids) {
my $pid = shift @pids;
my $host = delete $pid2host{$pid};
$active_count--;
if (!$line_mode) {
print "===" x 7, " $host ", "===" x 7, "\n";
}
if (!defined $pid) {
warn "ERROR: Failed to connect to host $host.\n";
delete $conns{$host};
next;
}
my $exit = 0;
my $ret = waitpid($pid, 0);
$exit = ($? >> 8);
delete $conns{$host};
unless ($ret > 0) {
#redo if ($! == EINTR);
warn "$host: ERROR: waitpid($pid) failed: $!\n";
next;
}
my $outfile = shift @outs;
my $in;
if (!open $in, $outfile) {
warn "ERROR: Can't open $outfile for reading: $!\n";
next;
}
while (<$in>) {
chomp;
if ($line_mode) {
print "$host: ";
}
print "$_\n";
}
if ($exit > 0) {
if ($line_mode) {
print STDERR "$host: ";
}
warn "Remote command returns status code $exit.\n";
}
if (!$line_mode) {
print "\n";
}
close $in;
unlink $outfile;
}
}
## HERE...
sub help ($) {
my $exit_code = shift;
my $msg = <<'_EOC_';
USAGE:
atnodes [OPTIONS] COMMAND... -- HOST_PATTERN... [OPTIONS]
atnodes [OPTIONS] COMMAND HOST_PATTERN... [OPTIONS]
OPTIONS:
-c <num> Set SSH concurrency limit. (default: 20,
when -tty is on, this setting will no use)
-h Print this help.
-l List the hosts and do nothing else.
-L Use the line-mode output format, i.e., prefixing
every output line with the machine name.
(could be controlled by the env SSH_BATCH_LINE_MODE)
-p <port> Port for the remote SSH service.
-ssh <path> Specify an alternate ssh program.
(This overrides the SSH_BATCH_SSH_CMD environment.)
-t <timeout> Specify timeout for net traffic.
-u <user> User account for SSH login.
-v Be verbose.
-w Prompt for password (used for login and sudo,
could be privided by SSH_BATCH_PASSWORD).
-P Prompt for passphrase (used for login,
could be privided by SSH_BATCH_PASSPHRASE).
-tty Pseudo-tty.
_EOC_
if ($exit_code == 0) {
print $msg;
exit(0);
} else {
warn $msg;
exit($exit_code);
}
}
sub check_openssh_version ($) {
my $ssh_cmd = shift;
my $version_info = `$ssh_cmd -V 2>&1`;
if ($version_info && $version_info =~ /^OpenSSH_(\d+\.\d+)/) {
my $v = $1;
if ($v && $v < 4.1) {
die "OpenSSH version $v, should be >= 4.1!\n";
}
}
}
__END__
=encoding utf-8
=head1 NAME
atnodes - Run commands on clusters
=head1 SYNOPSIS
# run a command on the specified servers:
$ atnodes $'ps -fe|grep httpd' 'ws[1101-1105].as.com'
# multiple-arg command requires "--":
$ atnodes ls /opt/ -- '{ps} + {as}' 'localhost'
# or use single arg command:
$ atnodes 'ls /opt/' '{ps} + {as}' 'localhost' # ditto
# specify a different user name and SSH server port:
$ atnodes hostname '{ps}' -u agentz -p 12345
# use -w to prompt for password if w/o SSH key (no echo back)
$ atnodes hostname '{ps}' -u agentz -w
# or prompt for password if sudo required...
$ atnodes 'sudo apachectl restart' '{ps}' -w
# use -P to prompt for passphrase (no echo back)
$ atnodes hostname '{ps}' -u agentz -P
# run sudo command if tty required...
$ atnodes -tty 'sudo apachectl restart' '{ps}'
# or specify a timeout:
$ atnodes 'ping foo.com' '{ps}' -t 3
=head1 USAGE
atnodes [OPTIONS] COMMAND... -- HOST_PATTERN... [OPTIONS]
atnodes [OPTIONS] COMMAND HOST_PATTERN... [OPTIONS]
=head1 OPTIONS
-c <num> Set SSH concurrency limit. (default: 20,
when -tty is on, this setting will no use)
-h Print this help.
-l List the hosts and do nothing else.
-L Use the line-mode output format, i.e., prefixing
every output line with the machine name.
(could be controlled by the env SSH_BATCH_LINE_MODE)
-p <port> Port for the remote SSH service.
-ssh <path> Specify an alternate ssh program.
(This overrides the SSH_BATCH_SSH_CMD environment.)
-t <timeout> Specify timeout for net traffic.
-u <user> User account for SSH login.
-v Be verbose.
-w Prompt for password (used for login and sudo,
could be privided by SSH_BATCH_PASSWORD).
-P Prompt for passphrase (used for login,
could be privided by SSH_BATCH_PASSPHRASE).
-tty Pseudo-tty.
=head1 PREREQUISITES
C<atnodes> (as well as the other scripts bundled by L<SSH::Batch>) requires the OpenSSH I<client> executable (usually spelled "ssh") with multiplexing support (at least OpenSSH 4.1). To check your C<ssh> version, use the command:
$ ssh -v
On my machine, it echos
OpenSSH_4.7p1 Debian-8ubuntu1.2, OpenSSL 0.9.8g 19 Oct 2007
usage: ssh [-1246AaCfgKkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]
[-D [bind_address:]port] [-e escape_char] [-F configfile]
[-i identity_file] [-L [bind_address:]port:host:hostport]
[-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-R [bind_address:]port:host:hostport] [-S ctl_path]
[-w local_tun[:remote_tun]] [user@]hostname [command]
There's no spesial requirement on the server side ssh service. Even a non-OpenSSH server-side deamon should work as well.
=head1 DESCRIPTION
Please refer to L<SSH::Batch> for more documentation.
=head1 SEE ALSO
L<fornodes>, L<tonodes>, L<key2nodes>, L<SSH::Batch>, L<Net::OpenSSH>.
=head1 AUTHORS
=over
=item *
Zhang "agentzh" Yichun (章亦春) C<< <agentzh@gmail.com> >>
=item *
Liseen Wan (万珣新) C<< <liseen.wan@gmail.com> >>
=back
=head1 COPYRIGHT & 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, 2010, 2011, Zhang "agentzh" Yichun (章亦春). 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.