1

我在通过 IO::Socket::Inet 与外部系统通信时遇到问题。我尝试登录并向系统发送多个命令,但不幸的是,如果第 58 行中的命令打印在条件语句下,这将不起作用。这种情况下的条件语句是处理响应数据所必需的。

package Net::Cli::Cisco;

use 5.006;
use strict;
use warnings FATAL => qw(all);

use IO::Socket::INET;
use Carp;

use Data::Dumper;
$| = 1;

sub new {
    my $class = shift;
    my %args  = @_;
    my $self  = bless {
        _host     => $args{host}     || carp('No hostname defined'),
        _username => $args{username} || carp('No username defined'),
        _password => $args{password} || carp('No password defined'),
        _logged_in => 0,
    }, $class;
    return $self;
}

sub connect {
    my $self = shift;
    my $host = $self->{_host};
    my $port = 23;

    my $handle = IO::Socket::INET->new(
        Proto    => "tcp",
        PeerAddr => $host,
        PeerPort => $port,
        Type     => SOCK_STREAM,
        Timeout  => 3
    ) or die "can't connect to port $port on $host: $!";

    my $shc = "\r\n";
    $self->{shc}    = $shc;
    $self->{handle} = $handle;
}

sub getInterface {
    my ($self) = @_;
    $self->connect;
    my @cmd_list = ( "sh clock", "sh ip int brief" );
    $self->send_cmd(@cmd_list);
}

sub send_cmd {
    my ( $self, @cmd_list ) = @_;
    my $handle = $self->{handle};
    my $response;
    while ( $response = <$handle> ) {

        if ( $response =~ m/^Username:/ ) {
            print "Conditional statements exec done!\n";
            print $handle $self->{_username} . $self->{shc};
        }

        #print $handle $self->{_username} . $self->{shc};
        print $response;
        print $handle $self->{_password} . $self->{shc};
        print $handle "enable" . $self->{shc};
        print $handle $self->{_password} . $self->{shc};
        print $handle "term leng 0" . $self->{shc};

        foreach my $cmd (@cmd_list) {
            print $handle "$cmd" . $self->{shc};
        }
        print $handle "exit" . $self->{shc};

    }

    close($handle);
}

1;

my $x = __PACKAGE__->new(
    "host"     => "1.1.1.1",
    "username" => "user",
    "password" => "pw"
);
$x->getInterface;

好吧,我不明白为什么我的代码是错误的。注意:如果我推荐第 61 行,一切正常。有任何想法吗?

4

1 回答 1

0

在 ikegami 发表评论后,请在下面找到工作子程序:

sub send_cmd {
my ( $self, @cmd_list ) = @_;
my $handle = $self->{handle};
my $response;
START: while ( $response = <$handle> ) {
        print $response;
        if ( $response =~ m/[^Username:|^Password:|\$%#:>]/ ) {
            print $handle $self->{_username} . $self->{shc};
            print $handle $self->{_password} . $self->{shc};
            print $handle "enable" . $self->{shc};
            print $handle $self->{_password} . $self->{shc};
            print $handle "term leng 0" . $self->{shc};
            foreach my $cmd (@cmd_list) {
              print $handle "$cmd" . $self->{shc};
            }

            print $handle "exit" . $self->{shc};
        } else {
            goto START;
        }
    }
close($handle);
于 2013-07-24T12:48:31.660 回答