r4617 minor changes in port linker
[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;
879ad6da
AA
62my $t = $op_timeout;
63my $m = 'die';
7cb57a03 64while (! $session->eof) {
879ad6da
AA
65 $buff .= $session->get (Timeout => $t, Errmode => $m);
66 $t = $op_timeout;
67 $m = 'die';
7cb57a03
AA
68 print $1 if ($buff =~ s/(.*\n)//s);
69
70 if (! $cmd_finished && (! defined $prompt_re || $buff =~ $prompt_re)) {
879ad6da
AA
71 if (defined $prompt_re and $op_delay) {
72 if (IO::Select->select ($sel, undef, undef, $op_delay)) {
73 unless ($session->eof) {
74 # something is received, no prompt detection at this time
75 # set NOHANG options for next reading, cause it can be telnet control sequence
76 $t = 0;
77 $m = 'return';
78 next;
79 }
80 }
81 }
7cb57a03
AA
82 my $cmd = <STDIN>;
83 if (defined $cmd) {
9f1da7de
AA
84 # replace all CR and LF symbols with single trailing LF
85 $cmd =~ s/[\015\012]//g;
86 $cmd .= "\012";
7cb57a03
AA
87 $session->put($cmd);
88 }
89 else {
90 $cmd_finished = 1;
91 $session->shutdown(1); # half-closing TCP connection (nothing to write)
92 }
93 }
94}
95print $buff;