[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Net::SSH & passing session
From:       Jamis Buck <jamis () 37signals ! com>
Date:       2005-09-30 18:00:56
Message-ID: 49E4FC69-C90E-4469-8A93-CF7DC5C48725 () 37signals ! com
[Download RAW message or body]

On Sep 30, 2005, at 11:36 AM, kilim wrote:

> Hello,
>
> I can make a connection using the examples provided in the
> documentation.
>
> But if I try to make it more 'clean', as shown bellow, I get the
> session returned, but I can't seem to do anything with it.
>
> Can you help me with this ?
>
> Thanks !
>
> This is the code:
>
>
> require 'net/ssh'
>
> class MySSH
>   def initialize(host, port, user, password)
>     @host = host
>     @port = port
>     @user = user
>     @password = password
>   end
>
>   def myConnection
>     begin
>       session = Net::SSH::Session.new(@host, @port, @user, @password )
>     rescue SocketError
>       raise(IOError, 'Could not connect to host')
>     rescue Net::SSH::AuthenticationFailed
>       raise(IOError, 'Authentication Failed')
>     end
>     return session
>   end
> end # of class
>
> a = MySSH.new( "localhost", 22, "aaa", "bbb" )
> puts "from inspect #{a.inspect}"
>
> # here you see that session is being returned
> puts "the value of a.myConnection is: #{a.myConnection}"
>
> # just to double check
> if a.myConnection.open?
>   puts "yep, connection is OPEN"
> end
>
> # Now this stuff below don't get 'seen' at all
> # and that is the real problem
> # How do I use the session once I pass it ?
> # -----------------------------------------
> a.myConnection.open_channel do |channel|
>   puts "open now, closing"
>   channel.close
> end
> a.myConnection.loop

The problem is that your #myConnection method isn't caching the  
session, so every time you call it, you're opening a new session.  
This means that the channel you try to open gets discarded, and the  
loop applies to a completely different connection.  Try this:

   def myConnection
     begin
       @session ||= Net::SSH::Session.new(@host, @port, @user,  
@password )
     rescue SocketError
       raise(IOError, 'Could not connect to host')
     rescue Net::SSH::AuthenticationFailed
       raise(IOError, 'Authentication Failed')
     end
   end


- Jamis

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic