2011-04-11 69 views
2

我嘗試以下通過一箇中央管理服務器爲「SSH跳」服務器訪問路由器Perl的SSH連接執行遠程登錄


#!/usr/bin/perl -X 

use strict; 
use Net::OpenSSH; 
use Net::Telnet; 

my $lhost = "linuxserver"; 
my $luser = "linuxuser"; 
my $lpass = "linuxpassword"; 

my $chost = "routername"; 
my $cpass = "Routerpassword"; 

my $prompt = '/(?:Password: |[>])/m'; 
my @commands = ("show users\r"); 

my $ssh = Net::OpenSSH->new($lhost, 
'user' => $luser, 
'password' => $lpass, 
'master_opts' => [ '-t' ], 
#'async' => 1 # if enabled then password cannot be set here 
); 
my ($pty, $err, $pid) = $ssh->open2pty("telnet $chost"); 

my $t = new Net::Telnet(
-telnetmode => 0, 
-fhopen => $pty, 
-prompt => $prompt, 
-cmd_remove_mode => 1, 
-output_record_separator => "\r", 
#-dump_log => "debug.log", 
); 

my $end = 0; 

while (!$end) { 
    my ($pre, $post) = $t->waitfor($prompt); 
    if ($post =~ /Password: /m) { 
    # send password 
    $t->print("$cpass"); 
    } 
    elsif ($post =~ /[>#]/ && @commands) { 
    my $cmd = shift(@commands); 
    if ($cmd !~ /[\r\n]/) { 
     $t->print($cmd); 
    } 
    else { 
     print $t->cmd($cmd); 
    } 
    } 
    else { 
    $end = 1; 
    $t->cmd("exit"); 
    } 
} 
#close $pty; 
$t->close(); 

不幸的是,我總是得到以下錯誤: 讀取錯誤:輸入/輸出錯誤在test.pl線71

有人可以幫助我,或者有沒有更好的解決方案,只測試通過「跳」服務器的telnet連接是否可能?

連接看起來像: 工作站--ssh->服務器--telnet->路由器

在此先感謝。

+0

它看起來像你正在遠程ssh主機上運行'telnet'並試圖連接你的ssh tty到一個新的'Net :: Telnet'會話。這是行不通的。也許看看Expect? http://search.cpan.org/~rgiersig/Expect-1.21/Expect.pod – friedo 2011-04-11 14:42:24

+0

我只想檢查是否可以從管理服務器到路由器的Telnet會話。我只能通過SSH連接到管理服務器,並通過telnet連接到路由器。所以如果還有其他的可能性,我也會用那個。但我真的是新的Perl,所以我需要更多的幫助:-) – Stefan 2011-04-11 15:08:12

回答

2

我認爲最好的選擇是建立一個SSH隧道到你的管理服務器,並用它來遠程登錄路由器。

2

獲得Net::TelnetNet::OpenSSH上工作有時不像應該那樣容易,它需要一些實驗才能找到正確組合的標誌和調用使其工作。

例如,如果不通過目標主機,請使用netcat打開一個原始連接(或者如果代理上允許隧道,則支持TCP轉發Net::OpenSSH)。

Expect + Net::OpenSSH可能是一個更好的選擇。