通过 perl 脚本执行命令 telnet [英] execute command telnet via perl script

查看:53
本文介绍了通过 perl 脚本执行命令 telnet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

Here is an image of the result when login normaly via 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 与模式匹配的字符串如何看起来完全一样,但在模式中添加一些空格可能就足够了.

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

这样,您将获得图片结束行的最后一个破折号,然后可能是一些空格,即 \n,后跟 >.

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 >.

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

更新:进一步了解 Net::Telnet 文档 我认为第一个例子在这里非常有用.文档这样说关于prompt.

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

此方法设置用于在输入流中查找提示的模式.它必须是表示有效 perl 模式匹配运算符的字符串.方法 login() 和 cmd() 尝试读取直到匹配提示.如果您选择的模式与远程端发送的模式不匹配,它们将因超时错误而失败.

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.

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.

这篇关于通过 perl 脚本执行命令 telnet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆