package sshConnector; sub new { my $class = shift; my $deviceInfo = shift; my $self = {}; my $ssh2; my ($ip,$port,$username,$password) = @$deviceInfo; # Invoke an ssh connection to the device eval { $ssh2 = Net::SSH2->new(); $ssh2->connect($ip,$port) or die }; if ($@) { print "Failed to make connection $@\n"; return 1; } # Send credentials for authentication my $res; if ($res = $ssh2->auth_keyboard($username, $password)) { $self->{'HANDLE'} = $ssh2; } return $self; } sub cmd { my $self = shift; my $cmd = shift; my $bufLength = 10000; my $connHandle = $sshHandle->channel(); # Make the connection blocking - wait until cmd exits $connHandle->blocking(1); # Merge the stderr contents also into the stdout buffer $connHandle->ext_data('merge'); # Execute the command eval { $connHandle->exec($cmd); }; if ($@) { print "Failed to execute cmd\n"; return 1; } # Initialize the buffer with all 0s $buf = '0' x $bufLength; # Read the buffer if anything is present in the output $connHandle->read($buf,$bufLength)) { $output = $buf; $exitStatus = $connHandle->exit_status(); print "output is $output, exit status is $exitStatus\n"; $connHandle->exec('exit'); $connHandle->close; return ($exitStatus,$output); } 1;