我正在尝试使用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 与模式匹配的字符串看起来如何,但在模式中添加一些空格可能就足够了。
$telnet->waitfor('/-\s*>/');
这样,您将获得图片结束线的最后一个破折号,然后可能是一些空格,即 \n
,后跟 >
。
另请查看https://regex101.com/r/eQ2pR0/1 .
更新:进一步了解 Net::Telnet documentation我认为第一个例子在这里非常有用。 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");
因为路由器的提示中没有任何信息,只需将其设置为“字符串开头,>
”和一个空格即可。
关于perl - 通过perl脚本执行telnet命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31877134/