无法在条件语句中将数据发送到IO :: Socket :: INET

时间:2013-07-24 08:14:29

标签: perl

我有问题通过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行一切正常。 有什么想法吗?

1 个答案:

答案 0 :(得分: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);