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