我是Perl脚本的新手,并尝试将一个perl代码写入ssh到路由器,然后在路由器上运行scp export命令(scp从路由器导出到远程目标服务器)。
#!/usr/local/bin/perl
use Net::SSH::Expect;
use warnings;
$hostname = "Router";
my $ssh = Net::SSH::Expect->new (
host => $hostname,
password=> 'abcd',
user => 'admin',
raw_pty => 1,
timeout => 150,
);
my $login_output = $ssh->login();
if ($login_output !~ /Router/) {
die "Login has failed. Login output was $login_output";
}
$ssh->send("scp export log traffic start-time equal 2013/04/01\@00:00:00 to user\@192.168.1.1:<path> end-time equal 2013/04/01\@01:00:00",3);
$ssh->waitfor('user@192.168.1.1\'s password:\s*') or die "prompt 'password' not found";
$ssh->send("abcd");
$ssh->send("\n");
sleep 100;
my $logout = $ssh->close();
print "=" x 50;
print "\n";
我能够看到脚本登录路由器很好(每次运行脚本时我都可以在路由器上看到新用户)。但是,几秒钟后,脚本将终止并显示错误: SSHProcessError ssh进程已终止。在cron1第22行
第22行有什么问题:$ ssh-&gt; waitfor('user@192.168.1.1 \'s密码:\ s *')或死于“提示'密码'未找到”;
答案 0 :(得分:0)
当$ hostname无效时,我遇到了同样的问题。做一个简单的主机名检查首先为我修复..
die "Host $hostname not found" unless gethostbyname($hostname);
更新: 似乎任何ssh连接错误都会导致SSHProcessError错误。
答案 1 :(得分:0)
我使用了不同的方法登录服务器。用这段代码制作了一个函数,每次都为我工作正常。看看这是否可以帮助你..
sub connect {
my $host =shift;
my $password=shift;
my $user=shift;
my $counter=0;
my $login_output;
$ssh = Net::SSH::Expect->new (
host => "$host",
password=> "$password",
user => "$user",
raw_pty => 1
);
$login_output = $ssh->run_ssh();
LABLE_login: # Lable used for looping
$login_output=$ssh->read_all();
if( $login_output =~ /yes/){ # To check if you are logging in for the first time
$ssh->send("yes\n");
sleep(2);
$login_output=$ssh->read_all();
if( $login_output =~ /Password/){
$ssh->send("$password\n");
}
}
elsif( $login_output =~ /Password/)
{
$ssh->send("$password\n");
}
else
{
sleep(2);
$counter++;
if($counter eq 3)
{ print color('red');print "Cannot connect to host exiting now\n";print color('reset');exit();}
goto LABLE_login;
}
$login_output=$ssh->send("$password\n");
return $ssh;
}