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