以下功能登录路由器,执行命令获取IPsec会话状态,并将接口名称和IP地址作为字符串返回。我想要函数返回哈希数组,而不是返回一个字符串。有人可以帮我解决这个问题吗?
sub cryptoSessionStatus {
my ($self,$interface) = @_;
my $status = 0;
my $peer_ip = 0;
#command to check the tunnel status
my $cmd = 'command goes here ' . $interface;
#$self->_login();
my $tunnel_status = $self->_login->exec($cmd);
#Regex to match the 'tunnel status' and 'peer ip' string in the cmd output
#Session status: DOWN/UP
#Peer: x.x.x.x
foreach my $line ( $tunnel_status ) {
if ( $line =~ m/Session\s+status:\s+(.*)/ ) {
$status = $1;
}
if ( $line =~ m/Peer:\s+(\d+.\d+.\d+.\d+)/ ) {
$peer_ip = $1;
}
}
return ($status,$peer_ip);
}
函数调用:
my $tunnel_obj = test::Cryptotunnels->new('host'=> 'ip');
my $crypto_sessions = $tunnel_obj->cryptoSessionStatus("tunnel1");
答案 0 :(得分:1)
这应该这样做:
my @session_states;
my $status;
foreach my $line ( $tunnel_status ) {
if ( $line =~ m/Session\s+status:\s+(.*)/ ) {
$status = $1;
}
if ( $line =~ m/Peer:\s+(\d+.\d+.\d+.\d+)/ ) {
push @session_states, { ip => $1 , status => $status };
$status = ""
}
}
return \@session_states;
#
# called like so
#
my $tunnel_obj = test::Cryptotunnels->new('host'=> 'ip');
my $crypto_sessions = $tunnel_obj->cryptoSessionStatus("tunnel1");
for my $obj (@$crypto_sessions) {
print $obj->{ip}, "\n";
print $obj->{status}, "\n";
}
这假设{<1}}行在输出中的Session status
行之前出现。如果是相反的(你没有提供路由器输出的样本,那么我必须猜测一下......)即:如果Peer
行在{{1}之前那么它应该是这样的:
Peer
算法没有真正的区别 - 输出中的第二位 - Session status
或my @session_states;
my $peer_ip;
foreach my $line ( $tunnel_status ) {
if ( $line =~ m/Session\s+status:\s+(.*)/ ) {
push @session_states, { ip => $peer_ip , status => $1 };
$peer_ip = "";
}
if ( $line =~ m/Peer:\s+(\d+.\d+.\d+.\d+)/ ) {
$peer_ip = $1;
}
}
return \@session_states;
#
# called the same as above
#
- 定义条目的结尾,并使用两个条目创建一个哈希并推送到{ {1}}数组。