3

Here's the situation:

I have SSH access to ServerA

I have SFTP access to ServerB, but only from ServerA

I want to use Ruby to SSH into ServerA, then SFTP files from ServerB to ServerA.

I can connect to ServerA using the documentation from Net::SSH:

require 'net/ssh/gateway'

gateway = Net::SSH::Gateway.new('server_a', 'user')

gateway.ssh("server_a", "user") do |ssh|
  # how to SFTP into server_b here and run SFTP commands?
end

gateway.shutdown!

What I can't figure out is how to SFTP into ServerB from the context of ServerA?

jemminger
  • 5,133
  • 4
  • 26
  • 47
  • I don't think you can do this using only code running on the local machine -- I think you're going to need to initiate the A->B connection with code running on A. – Ernest Friedman-Hill Apr 29 '11 at 02:21

4 Answers4

1

You can declare scp method in Net::SSH::Gateway class.

I have copied similar ssh method and it works fine.

    class Gateway < Net::SSH::Gateway
      def scp(host, user, options={}, &block)
        local_port = open(host, options[:port] || 22)

        begin
          Net::SCP.start("127.0.0.1", user, options.merge(:port => local_port), &block)
        ensure
          close(local_port) if block || $!
        end
      end
    end
user2153517
  • 725
  • 7
  • 9
1

Extending the gateway library directly to net/sftp worked well for me:


class Net::SSH::Gateway
  def sftp(host, user, options={}, &block)
    local_port = open(host, options[:port] || 22)
    begin
      Net::SFTP.start("127.0.0.1", user, options.merge(:port => local_port), &block)
    ensure
      close(local_port) if block || $!
    end
  end
end
jodell
  • 1,057
  • 9
  • 20
1

Assuming you have your private keys setup, run:

$ ssh-add

And write something like this:

require 'net/ssh'

# Set :forward_agent => true so that it will automatically authenticate with server_b
Net::SSH.start('server_a', 'user', :forward_agent => true) do |ssh|
  puts ssh.exec!("scp -r server_b:dir_i_want_to_copy dir_to_copy_to/")
end
Luke Chadwick
  • 1,648
  • 14
  • 24
0

from a command line, you can specify a command to be executed on the server after SSH'ing into it

First google result: http://bashcurescancer.com/run_remote_commands_with_ssh.html

So you can imagine placing the ssh command in backticks in the Ruby code, then executing the SFTP command

#!/usr/bin/env ruby

`ssh myserver 'sftp another-server'`

Something to look into

noli
  • 15,927
  • 8
  • 46
  • 62