Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Net::SSH2 Interactive command example

by shooter (Novice)
on Jun 18, 2007 at 09:15 UTC ( [id://621761]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, Just a quick and hopefully easy question. I'm just wondering if any one can give me a dig out with a query I have with this module. I have been looking at the helpful examples of using this module on this site. I have been trying to use this module to do an interactive ssh command. For example to use a "tail -f" or a "snoop" command. Basically any command that should keep the channel open. However with this module the channel does not seem to be able to remain open. I am sure there is a work-around but I can't seem to find it. Any working example would be greatly appreciated. Many thanks , Shooter

Replies are listed 'Best First'.
Re: Net::SSH2 Interactive command example
by shmem (Chancellor) on Jun 18, 2007 at 10:27 UTC
    Net::SSH2 comes with Net::SSH2::Channel. Maybe you want to use that.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
      Thanks for the quick response Shmem. I should have stated that I had gone through Net::SSH2::Channel and cannot seem to find any argument that allows for the channel to stay open. It seems to me that this is a simple enough request and therefore it should exist somewhere within the module. Has anyone found a way to do this?
        It's the shell method of Net::SSH::Channel, as zentara points out below, but alas, his code doesn't seem to work for me.

        Seems that this module is somwhat quirky, I could get it work only with some delay between sending a command and reading its output, and then the diamond operator doesn't seem to work on the $chan2 filehandle, but the read method does (linux, perl5.8.8):

        #!/usr/bin/perl use Net::SSH2; my $ssh2 = Net::SSH2->new(); $ssh2->connect('somehost') or die; if ($ssh2->auth_password('user','password')) { #shell use my $chan2 = $ssh2->channel(); $chan2->shell(); print $chan2 "uname -a\n"; select(undef,undef,undef,0.2); my ($len, $buf); print $buf while ($len = $chan2->read($buf,512)) > 0; print $chan2 "who\n"; select(undef,undef,undef,0.2); print $buf while ($len = $chan2->read($buf,512)) > 0; $chan2->close; } else { warn "auth failed.\n"; }

        Those selects() could be replaced with calls to $chan2->poll(), which usage to find out is left as an excercise to the reader...

        --shmem

        _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                      /\_¯/(q    /
        ----------------------------  \__(m.====·.(_("always off the crowd"))."·
        ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Net::SSH2 Interactive command example
by zentara (Archbishop) on Jun 18, 2007 at 11:50 UTC
    Are you looking for channel shell use?
    #shell use my $chan2 = $ssh2->channel(); $chan2->shell(); print $chan2 "uname -a\n"; print "LINE : $_" while <$chan2>; print $chan2 "who\n"; print "LINE : $_" while <$chan2>; $chan2->close;

    I'm not really a human, but I play one on earth. Cogito ergo sum a bum
      For my code to work, I had to insert a line found in another thread on this wonderful site...

      $chan2 = $ssh2->channel(); $chan2->blocking(0); print $chan2 "tail -5 /var/log/authlog\n"; print "**$_" while <$chan2>;


      Hope this might help somebody else banging their head against the wall as was I.
        Well I didn't have to bang my head too long. I just started trying Net::SSH2 a few minutes ago and hit this problem. So I fire up Super Search and there's my answer. Wonderful site, indeed. Perlmonks rocks. And a big ++ to you, vdubjunkie.

        That didn't work for me but this does:
        $chan2 = $ssh2->channel(); $chan2->blocking(0); $chan2->exec("tail -5 /var/log/authlog\n"); print "**$_" while <$chan2>;
Re: Net::SSH2 Interactive command example
by shooter (Novice) on Jun 18, 2007 at 13:44 UTC
    Thanks for the replies lads. I had tried tinkering with the shell method myself in Net::SSH2 which was on the perlmonks website cause I thought this might be the workaround. Alas to no avail.It still closes the channel by it's own accord. I actually have this working on Net::SSH::Perl::Buffer module but the problem I have with this method is that it is so slow in connecting to the host.It seems to be slow in regard to the key exchange. I had seen a lot on the web in regard to how to quicken it up by installing Math::BigINT::GMP but I saw no reduction in the time it took to connect to the host so I went back to Net::SSH2. So I was hoping that Net::SSH2 would have the solution as it is quicker on connecting to the host. Another get-around is to use system (ssh $host tail -f /log/log.txt); and not use any Perl Modules but I feel this is almost cheating as I don't consider this true perl. Anyone got any ideas on how to get a "tail -f " to work with Net::SSH2 or am I just wasting peoples time here. Cheers, Shooter
      Could you show us your code. I've done a lot of development this last year using this module. I believe I used 'shell' when sending commands over the established channel. I don't recall it closing the channel but it's been awhile since I've written code with this module.

      I recall having a lot of problems with STDERR and this module. Is this what you are having difficulty with? From the channel module page it says:
      shell

      Start a shell on the remote host; calls process("shell").

      exec ( command )

      Execute the command on the remote host; calls process("exec", command). Note that only one of these requests can succeed per channel (cp. "exec" in perlfunc); if you want to run a series of commands, consider using shell instead.

      I recommend 'shell'. It worked well for me. Post the code and we'll check it out.

      BTW, while this module is still immature IMO (not even at 1.0 I think). David has done a fantastic job and it's far better than the original NET::SSH::PERL IMO. I've been able to hit a couple hundred Unix/Linux servers in a few minutes and run inventory reports. It's very speedy and does a great job. We're now using it to create user accounts and set passwords in minutes rather than days.

      Yeah it's archaic but we can't decide how to tie everything together with LDAP and I was tired of waiting for management to approve funding :-)
        Sorry for the delay in getting back to you. Apologies I just could not get to a computer yesterday. The Code I was using was the one taken from the perlmonks web-site.
        my $chan2 = $ssh2->channel(); $chan2->shell(); print $chan2 "hostname -a\n"; print "LINE : $_" while <$chan2>; print $chan2 "tail -f /var/adm/messages"; print "LINE : $_" while <$chan2>; $chan2->close;
        (In fact I tried various options on that perlmonks page without success.) The only difference being the "tail -f" command I used instead of "uname" or "who". I notice when I do a "tail -50000". The channel would stay open for as long as it took to get through the 50000 lines. So there is no problem with keeping the channel open as such.I think the problem lies when it is being an interactive real-time command like "tail -f" or "snoop" when I want to keep the channel up and for some reason it takes a snap-shot,or what's in it's buffer and then closes. Any help, greatly appreciated !!!!!!!!!!!!!!!!!!!!!!!. U235sentinel have you ever come across this before?. Regards, Shooter
      I think the reason that Net::SSH::Perl::Buffer was slow was that the compression level might have been too high. You can use Net::SSH::Perl::Comp to set the compression level lower. For example,

      my $comp = Net::SSH::Perl::Comp->new('Zlib',1);

      sets the compression level to 1, the valid levels being 0 to 9. The default is 5.

        Hello everyone I have been trying to use this kind of scripts to connect to a remote machine and execute some commands. I think the connection is well done, but the execution of commands is not working for me. This particular case is about: 1.- I connect via ssh to a linux machine 2.- I enter in a special mode with MML commands (machine to man language) typing 'mml' 3.- I do staff with this mml commands My script is failing in step 2. I just want to send this "mml" and it's not working :( :(
        if( $ssh2->connect($host) ) { if( $ssh2->auth_password($user,$pass) ) { print "connected.....\n"; #shell use my $chan = $ssh2->channel(); $chan->blocking(0); $chan->shell(); print "sending command....\n"; my $num = 10; while($num--){ sleep(1); } print $chan "mml\n"; select(undef,undef,undef,0.2); print $buf while ($len = $chan>read($buf,512)) > 0;
        I tried with several methods: print $chan, exec ('comand'), everything in this thread... but still not working. Any idea?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://621761]
Approved by varian
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-16 20:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found