2013-04-05 169 views
1

我正在執行perl腳本中的telnet命令,如下所示。如何在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不會被識別爲內部或外部命令。

can any 1 help me out pls? 在advanch中感謝

+0

你需要/要/必須使用CPAN模塊爲:( – 2013-04-05 12:57:48

回答

3

與外部進程(如telnet)的通信比您想象的要複雜得多,因爲您必須正確處理緩衝,等待輸入等等。

如果您確實需要完整的交互,則使用Expect(https://metacpan.org/module/RGIERSIG/Expect-1.21/Expect.pod)的規範方法。

如果您實際上不需要交互,那麼遠程命令運行程序如sshrsh(您可以從perl當然調用)就足夠了。

+0

的規範方式來處理這個是使用Expect(https://metacpan.org/module/RGIERSIG/Expect-1.21/Expect.pod),如果你真的需要完全互動。 – picnic4u 2013-04-11 07:37:17

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(); 
+0

我必須爲我的本地主機添加端口號碼,所以我怎麼能?你可以給我一些線索嗎? – picnic4u 2013-04-05 12:17:32

+0

'my $ t = new Net :: Telnet(Timeout => 5,Prompt => $ params {'default_prompt'},Port => $ port);'#你可以選擇完整的選項列表鰭d在cpan的頁面http://search.cpan.org/~jrogers/Net-Telnet-3.03/lib/Net/Telnet.pm – Suic 2013-04-05 12:20:06

0

在系統中安裝TCL(ActiveTcl8.5.13.0.296436-Win32的IX86-threaded.exe適用於Windows)。 然後從命令來自爲teacup install Expect

下面的腳本運行修正後安裝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. 
+0

上面的一個是我的工作代碼。 – picnic4u 2013-04-08 08:57:20

相關問題