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