通过 perl 脚本执行命令 telnet

execute command telnet via perl script

我正在尝试使用telnet 通过Perl 脚本执行命令,似乎下面的脚本能够成功登录,但无法执行命令。我找不到正确的正则表达式在执行命令之前等待提示 >

这是通过 telnet 正常登录时的结果图像:

#!/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');

您需要考虑到可能存在换行符。我不确定 Net::Telnet 与模式匹配的字符串看起来完全一样,但可能足以在模式中添加一些白色 space。

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

这样您将得到图片结束行的最后一个破折号,然后可能是一些白色space,这将是 \n,然后是 >

另请查看 https://regex101.com/r/eQ2pR0/1


更新:进一步进入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.

所以我认为你不需要使用 waitfor 而是使用 prompt.

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

因为路由器在提示符中没有任何信息,只需将其设置为“字符串的开头”,> 和 space 就可以了。