【问题标题】:how to run command on telnet command prompt in perl script如何在 perl 脚本中的 telnet 命令提示符下运行命令
【发布时间】:2013-03-27 18:08:04
【问题描述】:

我正在 perl 脚本中执行 telnet 命令,如下所示。

$telnetOutput = `telnet localhost 4505`;
print "\n telnet command output: $telnetOutput \n";

$clients = `clients`;
print"\n $clients\n";

$clientNumber_or_anyOtherKey = `1`;
print "\n $clientNumber_or_anyOtherKey \n";

$pollers = `pollers`;
print "\n $pollers\n";`

但是在运行 $telnetOutput = `telnet localhost 4505`;命令,我们知道它会打开 telnet 命令提示符,但所有其他命令仍在同一旧命令 prmopt 中执行,所以它说 clients1pollers 不被识别为内部或外部命令。

请问有哪位可以帮帮我吗? 提前感谢

【问题讨论】:

  • 你需要/应该/必须为此使用 cpan 模块:(

标签: linux perl tcl telnet perl-module


【解决方案1】:

与 telnet 等外部进程通信比您想象的要复杂,因为您必须正确处理缓冲、等待输入等。

如果您确实需要完全交互,典型的解决方法是使用 Expect (https://metacpan.org/module/RGIERSIG/Expect-1.21/Expect.pod)。

如果您实际上不需要交互,那么像 sshrsh(当然可以从 perl 调用)这样的远程命令运行程序就足够了。

【讨论】:

【解决方案2】:

这是 telnet 连接到 d-link des-1228 路由器并执行 2 个命令的工作示例。如果你想改变它:

#!/usr/bin/perl

use strict;
use warnings;
use Net::Telnet;

my $params;
$params{'login'}='root';
$params{'password'}='hardpass';
$params{'default_prompt'}='/DES-[^:]+:.#/'; #change it to regexp matching your prompt
my $host = '192.168.1.20';

my $t=new Net::Telnet(Timeout=>5, Prompt=>$params{'default_prompt'}, Errmode=>sub{next;});
$t->open(Host=>$host, Timeout=>2);
my $res=$t->login($params{'login'}, $params{'password'});
return if $res!=1;
$t->cmd('disable clipaging');
my @lines=$t->cmd('show fdb'); #output here
$t->close();

【讨论】:

  • 我必须为我的本地主机添加端口号。那我怎么能?你能给我一些线索吗?
  • my $t=new Net::Telnet(Timeout=>5, Prompt=>$params{'default_prompt'}, Port=>$port); #您可以在 cpan 页面上找到的选项的完整列表search.cpan.org/~jrogers/Net-Telnet-3.03/lib/Net/Telnet.pm
  • 什么是默认提示
【解决方案3】:

在系统中安装TCL(ActiveTcl8.5.13.0.296436-win32-ix86-threaded.exe for windows)。 然后安装Expect Package from Command from as teacup install Expect

修改需求后运行下面的脚本

#!/usr/bin/expect -f
#!usr/bin/expect
package require Expect
# Test expect script to telnet.

spawn telnet localhost portnumber
expect "TradeAggregator>"
send "3\r"
expect "Client:"
send "1\r"
expect "1-Client>"
send "2\r"
expect "Client Pollers"
send "2\r"
expect "1-NYMEX UTBAPI"
send "1\r"
expect "2-NYMEX UTBAPI"
send "Test_123\r"
expect "Are"
send "n\r"
send "exit\r"
send "exit\r"
send "exit\r"
# end of expect script.

【讨论】:

    猜你喜欢
    • 2014-03-18
    • 1970-01-01
    • 2021-08-28
    • 2016-11-21
    • 2015-10-30
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多