Search code examples
rubysshscp

Can I use exec and upload during the same SSH session?


I need to perform several operations during an ssh session. At the moment I am using SSH.start and SCP.start for the remote operations and uploads respectively. This is an example:

Net::SSH.start(host, user, options) do |session|
  output = session.exec!(cmd)
end   

Net::SCP.start(host, user, options) do |scp|
  scp.upload!(src, dst, :recursive => true)
  scp.upload!(src1, dst1, :recursive => true)
end

Net::SSH.start(host, user, options) do |session|
  output = session.exec!(cmd)
end

The problem is that for every operation the SSH connection needs to be re-established and this is affecting the overall performance.

Is there a way to open a session and then perform all the required operations such as commands, uploads and downloads?


Solution

  • The SSH protocol allows multiple channels per connection. So technically it is possible.

    I do not know Ruby net-ssh implementation, but from it's API it seems to support this.

    The constructor of Net::SCP class takes an exiting SSH session.

    # Creates a new Net::SCP session on top of the given Net::SSH +session+
    # object.
    def initialize(session)
    

    So pass your existing Net::SSH instance to the Net::SCP constructor, instead of starting a new session using .start method.