[英]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. 我正在尝试使用telnet通过Perl脚本执行命令,以下脚本似乎能够成功登录,但无法执行该命令。 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: 这是通过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');
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.
我不确定Net :: Telnet匹配该模式的字符串看起来到底是什么样子,但是可能足以在模式中添加一些空格。
$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 >
. 这样,您将获得图片末尾的最后一个破折号,然后是一些空格,可能是
\\n
,然后是>
。
Also check out https://regex101.com/r/eQ2pR0/1 . 另请查看https://regex101.com/r/eQ2pR0/1 。
Update : Going further into the Net::Telnet documentation I think the first example is pretty useful here. 更新 :进一步进入Net :: Telnet文档,我认为第一个示例在这里非常有用。 The docs say this about
prompt
. 这些文档是关于
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.
它必须是代表有效的perl模式匹配运算符的字符串。 The methods login() and cmd() try to read until matching the prompt.
方法login()和cmd()尝试读取直到匹配提示。 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
. 因此,我认为您不需要使用
waitfor
,而是使用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. 由于路由器没有在其提示的任何信息,只将其设置为“字符串的开头,
>
和一个空格应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.