r4518 files:
[racktables] / gateways / ssh
CommitLineData
7cb57a03
AA
1#!/usr/bin/perl
2
3use strict;
4use Getopt::Long;
5
6my @orig_params = @ARGV;
7
8# fetch command-line parameters
9my $op_help;
10my $op_port;
11my $op_connect_timeout = 2;
12my $op_user;
13my $op_identity;
14my $op_dont_sudo;
15my $op_as_user;
16GetOptions (
17 'h' => \$op_help,
18 'port|p:i' => \$op_port,
19 'connect-timeout:i' => \$op_connect_timeout,
20 'dont-sudo' => \$op_dont_sudo,
21 'sudo-user:s' => \$op_as_user,
22 'username|l:s' => \$op_user,
23 'identity|i:s' => \$op_identity,
24);
25if ($op_help) {
26 &display_help;
27 exit;
28}
29my $op_host = $ARGV[0];
30defined $op_host or die "ERROR: please specify remote host (-h for help)";
31
32&become_user;
33
34sub display_help {
35 print <<END;
36ssh batch client for RackTables.
37Takes commands list in standard input and gives the responses via standard output.
38Usage:
39$0 <hostname> [-p <port>] [-l <username>] [-i <identity file>] [--connect-timeout=<seconds>] [--as-user=<username>]
40 -p, --port TCP port number to connect to
41 -l, --username remote username for ssh
42 -i, --identity identity file to authenticate
43 --connect-timeout timeout for giving up connecting process, seconds
44 --as-user sudo self as specified username
45
46END
47}
48
49sub become_user {
50 if (defined $op_as_user && (my $uid = getpwnam($op_as_user)) != $>) {
51 if ($op_dont_sudo) {
52 die "Cant become user $op_as_user";
53 }
54 else {
55 exec ('sudo', '-u', "#$uid", $0, @orig_params, '--dont-sudo') or die "cant exec: $!";
56 }
57 }
58}
59
60my $port = $op_port || 22;
61my @params;
62push @params, '-T';
63if (defined $op_connect_timeout) {
64 push @params, '-o', "ConnectTimeout=$op_connect_timeout";
65}
66if ($port) {
67 push @params, '-p', $port;
68}
69if (defined $op_user) {
70 push @params, '-l', $op_user;
71}
72if (defined $op_identity) {
73 push @params, '-i', $op_identity;
74}
75push @params, '-o', 'StrictHostKeyChecking=no';
76push @params, '-o', 'BatchMode=yes';
77push @params, '-o', 'CheckHostIP=no';
78push @params, '-o', 'LogLevel=ERROR';
79
80exec ('ssh', @params, $op_host) or die "cant exec ssh: $!";