Perl: telnet dans un script perl
(Redirigé depuis Utiliser telnet dans un script perl)
1 #!/bin/env perl
2
3 use strict;
4
5 use Getopt::Long;
6 use FindBin;
7 use lib "$FindBin::Bin";
8
9 use Telnet ;
10
11 # Variables for telnet call
12 my $session ;
13 my $remoteaddr = "192.168.10.10" ;
14 my $username = "user1" ;
15 my $password = 'mypw' ;
16 my $port = 23 ;
17 my $response = "";
18
19 my $resultFile = "/tmp/dummylog.txt";
20
21 my $debug=1; # set 0 for no debug information
22 #-------------------------------------------------------------------------------
23 # show debug information
24
25 sub debug {
26 print @_ if ($debug);
27 }
28 #-------------------------------------------------------------------------------
29 # retrieve and evaluate the command's response
30
31 sub getResponse {
32 my @response = @_;
33 my $text = "";
34 foreach( @response ) {
35 $text = $text . $_;
36 }
37 return $text;
38 }
39 #-------------------------------------------------------------------------------
40 # retrieve and evaluate the command's response
41
42 sub sendCommandAndGetResponse {
43 my ($cmd, $prompt) = @_;
44
45 if ($prompt) {
46 $response = getResponse( $session -> cmd (String => "$cmd",
47 Timeout => 10 ));
48 } else {
49 $response = getResponse( $session -> cmd (String => "$cmd",
50 Timeout => 10, Prompt => "$prompt" ));
51 }
52 if( $response > "1" ) {
53 print "error: $response.\\n";
54 exit;
55 } else {
56 debug("$response.\\n");
57 }
58 }
59 #-------------------------------------------------------------------------------
60 # check options
61 #
62 usage() unless ( GetOptions(
63 "addr=s" , \\$remoteaddr,
64 "user=s" , \\$username,
65 "passw=s" , \\$password,
66 "outfile=s" , \\$resultFile,
67 )
68 );
69 # Start a Telnet session to remote address
70 if ( $remoteaddr ne "" ) {
71 eval { $session = Telnet -> new (Timeout => 10,
72 Prompt => "/.*$username #/",
73 # Prompt => "/System>/",
74 Port => $port) or exit ; };
75 if( $@ ) {
76 my $text = $@;
77 $text =~ s/.+://;
78 $text =~ s/at.*//;
79 print "Telnet session could not be instanciated: $text.\\n";
80 exit;
81 }
82 #
83 eval { $session -> open ($remoteaddr) ; };
84 if( $@ ) {
85 my $text = $@;
86 $text =~ s/.+://;
87 $text =~ s/at.*//;
88 print "$remoteaddr: Telnet could not be opened: $text.\\n";
89 exit;
90 }
91 #
92 debug("$remoteaddr: Telnet opened.\\n");
93
94 eval { $session -> login (Name => $username,
95 Password => $password) ; };
96 if( $@ ) {
97 debug("$remoteaddr: unsuccessful login attempt!\\n");
98 exit;
99 }
100 else {
101 debug("$remoteaddr: successfully logged in.\\n");
102 }
103 #
104 # prevent from receiving garbage
105 sendCommandAndGetResponse("uname -a");
106 debug ("server info: $response\\n");
107 }