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'
g开发者_如何学运维ateway = 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?
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
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
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
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
精彩评论