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