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