in reply to Printing Output From Net::SSH2 exec

Whats wrong with shell? Maybe:
#!/usr/bin/perl use warnings; use strict; use Net::SSH2; use Data::Dumper; # assuming a user named 'z' for demonstration # connecting to localhost, so you need your sshd running # see maillist archives at # http://lists.sourceforge.net/lists/listinfo/ssh-sftp-perl-users # for deeper discussions my $ssh2 = Net::SSH2->new(); $ssh2->connect('localhost') or die "Unable to connect Host $@ \n"; $ssh2->auth_password('z','ztester') or die "Unable to login $@ \n"; #shell use my $chan = $ssh2->channel(); $chan->blocking(0); $chan->shell(); print $chan "ls -la\n"; print "LINE : $_" while <$chan>; print $chan "who\n"; print "LINE : $_" while <$chan>; print $chan "date\n"; print "LINE : $_" while <$chan>; $chan->close; __END__

I'm not really a human, but I play one on earth.
Old Perl Programmer Haiku

Replies are listed 'Best First'.
Re^2: Printing Output From Net::SSH2 exec
by salva (Canon) on May 14, 2009 at 12:58 UTC
    $chan->shell(); print $chan "ls -la\n"; print "LINE : $_" while <$chan>; print $chan "who\n"; print "LINE : $_" while <$chan>; print $chan "date\n"; print "LINE : $_" while <$chan>;
    That is not reliable!

    The remote shell doesn't signal in any way when the commands run through it exit to its parent process, the ssh server. If the remote command does not run fast enough, the ... while(<$chan>) loop will finish without having read the full output, and the remaining data will be delayed until the next loop (or even later).

    Net::SSH::Expect that uses a similar approach, solves that problem examining the remote output, looking for the shell prompt in order to detect when a subcommand has finished.

      Indeed, I've had more success with shell, but as salva points out, occasionally I end up with partial output. The other thing is that it's hard to distinguish stderr from stdout when running a command under shell.

      It seems like Net::SSH2 has a new maintainer, so hopefully that module will start to see some improvement soon. In the meantime, it looks like Net::OpenSSH is the way to go for me.

      R
        Net::SSH2 is working for me. Commands that take a while to return back to shell are fine now:

        my $ssh2 = Net::SSH2->new();
        $ssh2->connect("$host") or die $!;
        my $chan = $ssh2->channel();
        $chan->blocking(1);
        $chan->exec("rpm -qa |wc|awk '{print \$1}'");
        $chan->read($buf, $len);
        my @output;
        while (<$chan>) { push(@output,$_); }
        my $stdout=join ("", @output);
        print $stdout;