godsown has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
I have a question regarding the Net::SSH2 module in ActiveState Perl for windows
I want to perform a for loop operation after connecting to a remote system. I have started a new shell from the channel module of Net::SSH2
In windows we need to provide the commands in the Channel's write method. But I do not know how to go ahead with writing a for loop using the write method.
Need some help pls.. Thx in advance..
J

Replies are listed 'Best First'.
Re: Net::SSH2 to execute for loop
by syphilis (Archbishop) on Jan 19, 2010 at 07:25 UTC
    Hi,

    This works for me on Win32, using Net::SSH2-0.18, built against an older version of libssh2, on perl-5.8:
    use Net::SSH2; use warnings; use strict; my $buflen = 10000; my $buf1 = '0' x $buflen; my $ssh2 = Net::SSH2->new(); $ssh2->connect('xxx.xxx.xxx.xxx') or die; $ssh2->auth_password('xxx','xxxxxxx') or die "Unable to login $! \n"; my $chan = $ssh2->channel(); $chan->blocking(0); $chan->shell(); for(1 .. 2) { if($_ == 1) {$chan->write("echo \$PATH\n")} else {$chan->write("echo \$HOME\n")} select(undef,undef,undef,0.25); $chan->read($buf1, $buflen); print "BUF1: ", $buf1, "\n"; } $chan->close;
    However, running Net::SSH2-0.28, built against the latest libssh2-1.2.2, the buffer is *empty* in the first iteration - but filled correctly in subsequent iterations of the loop.

    That is, with the older version of Net::SSH2 I'm getting:
    BUF1: /usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/usr/games:/home/rob +/bin BUF1: /home/rob
    but with the latest, I'm getting:
    BUF1: BUF1: /home/rob
    I can hack my way around the problem with the latest Net::SSH2 by changing the loop to:
    for($i = 0, $i < 2, $i++) { if($_ == 1) {$chan->write("echo \$PATH\n")} else {$chan->write("echo \$HOME\n")} select(undef,undef,undef,0.25); $chan->read($buf1, $buflen); if($buf1) {print "BUF1: ", $buf1, "\n"} else { print "Empty buffer ... trying again\n"; --$i; } }
    That then produces (running the latest Net::SSH2):
    Empty buffer ... trying again BUF1: /usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/usr/games:/home/rob +/bin BUF1: /home/rob
    Hope there's something there that helps. (I don't have time to "tune" this script at the moment - or to look at the issue with the latest version.)

    Cheers,
    Rob