1

我在 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被识别为内部或外部命令。

任何 1 可以帮助我吗?预先感谢

4

3 回答 3

3

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

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

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

于 2013-04-05T11:04:52.797 回答
1

这是 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();
于 2013-04-05T12:08:26.310 回答
0

在系统中安装TCL(ActiveTcl8.5.13.0.296436-win32-ix86-threaded.exe for windows)。Expect然后从命令安装包作为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.
于 2013-04-07T10:49:32.293 回答