Cleanup in files that is not php
[racktables] / gateways / telnet
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 use Net::Telnet;
10
11 # fetch command-line parameters
12 my $op_help;
13 my $op_port;
14 my $op_connect_timeout = 2;
15 my $op_timeout = 10;
16 my $op_prompt;
17 my $op_delay = 0;
18 GetOptions (
19 'h' => \$op_help,
20 'port:i' => \$op_port,
21 'connect-timeout:i' => \$op_connect_timeout,
22 'timeout:i' => \$op_timeout,
23 'prompt-delay:f' => \$op_delay,
24 'prompt:s' => \$op_prompt,
25 );
26 if ($op_help) {
27 &display_help;
28 exit;
29 }
30 my $op_host = $ARGV[0];
31 defined $op_host or die "ERROR: please specify remote host (-h for help)";
32 defined $op_prompt or die "ERROR: please specify prompt regexp (-h for help)";
33 my $prompt_re = qr/$op_prompt/;
34
35 sub display_help {
36 print <<END;
37 telnet batch client for RackTables.
38 Takes commands list in standard input and gives the responses via standard output.
39 Login credentials are not specially handled and should be placed as first lines of input
40 Usage:
41 $0 {hostname} [--port={port}] [--connect-timeout={seconds}] --prompt={regexp} [--timeout={seconds}]
42
43 port: TCP port number to connect to
44 connect-timeout: timeout for giving up connecting process, seconds
45 prompt: command prompt regexp for interactive telnet (auth prompts too)
46 timeout: wait time for activity of remote telnet peer in seconds
47
48 END
49 }
50
51 my $port = $op_port || 23;
52
53 my $session = Net::Telnet->new (
54 Host => $op_host,
55 Port => $port,
56 Timeout => $op_connect_timeout,
57 );
58
59 use IO::Select;
60 my $sel = new IO::Select($session);
61
62 my $buff = '';
63 my $nohang_read;
64 until ($session->eof) {
65 # read output from the device
66 eval {
67 $buff .= $session->get (Timeout => $nohang_read ? 0 : $op_timeout, Errmode => $nohang_read ? 'return' : 'die');
68 };
69 if ($@) {
70 # check if there is something else in <STDIN>
71 if (defined <STDIN>) {
72 die $@;
73 }
74 else {
75 last; # no more input, seems like session was closed remotely by our last command
76 }
77 }
78 $nohang_read = 0;
79 print $1 if ($buff =~ s/(.*\n)//s);
80
81 next unless ($buff =~ $prompt_re);
82 # send pending commands to the device
83 if ($op_delay and IO::Select->select ($sel, undef, undef, $op_delay)) {
84 # something is received, no prompt detection at this time
85 # set NOHANG options for next reading, cause it can be telnet control sequence
86 $nohang_read = 1;
87 }
88 elsif (defined ($_ = <STDIN>)) {
89 # replace all CR and LF symbols with single trailing LF
90 s/[\015\012]//g;
91 $session->put($_ . "\012");
92 }
93 else {
94 # no more commands in input
95 last;
96 }
97 }
98 print $buff;