Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SSH into a server and then SFTP from there to another server?

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?

like image 330
jemminger Avatar asked Feb 03 '26 21:02

jemminger


2 Answers

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
like image 128
Luke Chadwick Avatar answered Feb 06 '26 11:02

Luke Chadwick


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
like image 45
user2153517 Avatar answered Feb 06 '26 13:02

user2153517



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!