Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Getting variable sized reapones using Net::SSH2

by essej1 (Novice)
on Sep 06, 2012 at 15:50 UTC ( #992123=perlquestion: print w/ replies, xml ) Need Help??
essej1 has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to read the output of a command issued using Net::SSH2. For some reason if I do not set the buffer size in the $chan2->read to close to the length of result the command does not finish. The output length is varies from about 20 bytes to over 2048. If I turn on debug ($ssh2->debug(1);) I see bytes being read but no completion. I've tried the two blocking's (ssh and channel) to no avail. I have similar issues with the write and exec options. Is there a better way to do this ? Keep in mind that I'm not the most powerful Perl programmer. And no I can't use expect. Sample code:

#!/opt/csw/bin/perl use strict; use warnings; use Net::SSH2; use constant BUFLEN => 10_0000; my $host = "<name or IP>"; my $user = "<ID>"; my $pass = "<password>"; my $buf; my $ssh2 = Net::SSH2->new(); my $ok = 1; print "==> $host\n"; $ssh2->connect($host) or $ok = 0; if ( !$ok ) { print "Probable telnet\n"; exit(1); } if ( !$ssh2->auth_password( $user, $pass ) ) { print "==> 4 pass fail\n"; exit(1); } my $chan2 = $ssh2->channel(); $chan2->shell(); print $chan2 ("term len 0\n"); $chan2->read( $buf, BUFLEN ); print $buf; print $chan2 ("dir\n"); $chan2->read( $buf, BUFLEN ); print $buf;

Comment on Getting variable sized reapones using Net::SSH2
Download Code
Re: Getting variable sized reapones using Net::SSH2
by Illuminatus (Curate) on Sep 06, 2012 at 17:58 UTC
    It seems that the read method is exact; if you're blocking, then it will wait for as many chars as you ask for. There is an undocumented method in Channel called READLINE. Changing your last 3 lines thusly:
    my @buf; print $chan2 ("ls -l\n"); @buf = $chan2->READLINE(); print @buf;
    and keeping the buflen large (at 10K) gave me the results without hanging.

    fnord

      Thanks. It works like a champ. Got to love undocumented features. While messing around I also found this may also work. I think your's is probably better.

      print $chan2 "\ndir\n"; while (<$chan2>) { print "$_"; }
      Paradise: Florida, full tank of gas, no appointments.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://992123]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2014-09-24 00:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (243 votes), past polls