0

I have a few methods doing this:

def method_a
    Net::SSH.start(...) do |ssh|
    end
end

def method_b
    Net::SSH.start(...) do |ssh|
    end
end
def method_c
    Net::SSH.start(...) do |ssh|
    end
end

Each methods call Net::SSH start which are individual SSH sessions, doing different things.

Is there a way to reuse Net::SSH session so that all 3 methods utilize a single session?

THanks.

3 Answers 3

0

The way to go in Net::SSH is to put

@ssh_session = Net::SSH.start( @host, nil, option={:config => true})

to a variable and then on each methods

def method_a
    @ssh_session.exec!("Hello a")
end

def method_b
     @ssh_session.exec!("Hello b")
end
def method_c
     @ssh_session.exec!("Hello c")
end

And of course i place all the above in a class, so that I can initialize and start a ssh session and exec commands without re-establishing SSH.

Sign up to request clarification or add additional context in comments.

Comments

0

Outside a class, you can try:


def call
  Net::SSH.start(...) do |ssh|
    method_a(ssh)
    method_b(ssh)
    method_c(ssh)
  end
end

def method_a(ssh)
  ssh.exec(...) 
end

def method_b(ssh)
   ssh.exec(...)
end

def method_c(ssh)
   ssh.exec(...)
end
If it's in a class, you can define `attr_reader :ssh` and then initialize it thus:
attr_reader :ssh

def initialize
  @ssh ||= Net::SSH.start(...)
end

With that, you can simply define

def method_a
  ssh.exec(...)
end

Same applies for other methods. I hope this helps?

1 Comment

@ydanjiu, ur second method, in a class is what I've already answered. but for the first method. the call calls all 3 methods which is not what I wanna achieve.
-1

Yes, definitely you can make it DRY.

You can add one method which accept hostname for the Net::SSH connection as below:

def ssh_exec(hostname)

  Net::SSH.start( hostname, 'user', :timeout => 5, :paranoid => false ) do |ssh|

   ....
  end
end

Then you can call this method ssh_exec() with proper hostname wherever you need it...

1 Comment

thanks but I re-edit my question to be clearer. your solution doesn't work since each methods ssh block runs different stuff. Also its not about making code DRY, its about reusing the SSH session for all 3 sessions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.