Search code examples
perltelnet

execute command telnet via perl script


I'm trying to excute a command via a Perl script using telnet, it seem that the script below is able to log in successfully, but can't execute the command. I coudn't find the right regular expression that will wait the prompt > before executing the command.

Here is an image of the result when login normaly via telnet:

screenshot

#!/usr/bin/perl
use strict;
use warnings;
use Net::Telnet;
my $remote_host = 'myrouter';
my $telnet = new Net::Telnet  (Timeout=>10  ,Input_log => "received_data.txt" );
$telnet->open($remote_host);
$telnet->waitfor('/ADSL2PlusRouter login:/i');
$telnet->print('mylogin'); 
$telnet->waitfor('/Password:/i');
$telnet->print('my_password');
$telnet->waitfor('/-*>/');
$telnet->cmd("adsl show");
$telnet->print('exit');

Solution

  • You need to take into account that there is probably a line break character. I'm not sure how the string that Net::Telnet matches the pattern against looks like exactly, but it's probably enough to add some whitespace into the pattern.

    $telnet->waitfor('/-\s*>/');
    

    This way you will have the last dash of the picture's end line, then maybe some whitespace, which would be a \n, followed by the >.

    Also check out https://regex101.com/r/eQ2pR0/1.


    Update: Going further into the Net::Telnet documentation I think the first example is pretty useful here. The docs say this about prompt.

    This method sets the pattern used to find a prompt in the input stream. It must be a string representing a valid perl pattern match operator. The methods login() and cmd() try to read until matching the prompt. They will fail with a time-out error if the pattern you've chosen doesn't match what the remote side sends.

    So I think you don't need to use waitfor but instead use prompt.

    $telnet->print('my_password');
    $telnet->prompt('/^> /');
    $telnet->cmd("adsl show");
    

    Because the router doesn't have any information in its prompt, just setting it to 'beginning of string, > and a space should work.