package Foo; use v5.14; use strict; use warnings; use Carp; use Moose; use MooseX::StrictConstructor; use Net::SSH2; has 'hostname' => ( isa => 'Str', is => 'rw', ); has 'username' => ( isa => 'Str', is => 'rw', ); has 'password' => ( isa => 'Str', is => 'rw', ); has 'command' => ( isa => 'Str', is => 'rw', ); has '_ssh2_connection' => ( is => 'bare', isa => 'Object', ); has '_ssh2_channel' => ( is => 'bare', isa => 'Object', ); ## # Connect to server using provided parameters. # sub connect { my $self = shift; ## # Net::SSH2 connection object. # my $connection = Net::SSH2->new(); # Connect to server. $connection->connect($self->hostname()) or croak "Unable to connect to " . $self->hostname() . ": $@\n"; $connection->auth_password($self->username(),$self->password()) or croak "Unable to authenticate to " . $self->hostname() . " as " . $self->username . ": $@\n"; ## # Net::SSH2::Channel object. # my $channel = $connection->channel(); # Open Net::SSH2::Channel shell so that multiple commands # can be executed. $channel->blocking(0); $channel->shell(); # Manually flush channel. Uncertain why this must be done, but # when used in an object wrapper, execute() will fail later if # it is not. using $channel->flush() doesn't do the trick. print $channel "\n"; while (<$channel>) { chomp; push my @tmp,"$_\n"; } # Attach connection and channel to object. $self->{_ssh2_channel} = \$channel; $self->{_ssh2_connection} = \$connection; return 1; } ## # Disconnect from server. # sub disconnect { my $self = shift; # Close Net::SSH2 objects. ${$self->{_ssh2_channel}}->close() if (defined ${$self->{_ssh2_channel}}); ${$self->{_ssh2_connection}}->disconnect() if (defined ${$self->{_ssh2_connection}}); # Delete Net::SSH2 objects. $self->{_ssh2_channel} = undef; $self->{_ssh2_connection} = undef; return 1; } ## # Execute command specified by 'command' attribute. # sub execute { # Initialize variables. my $self = shift; #my $channel = ${$self->{_ssh2_channel}}; my $channel = $self->{_ssh2_channel}; my @return_data; my $cmd = $self->command(); # Execute command and process return data. #print $channel "$cmd\n"; #while (<$channel>) { print {${$channel}} "$cmd\n"; while (<${$channel}>) { chomp; push @return_data,"$_\n"; } # Return array ref to caller. return \@return_data; } 1; # End of module. __PACKAGE__->meta->make_immutable; __END__