Class: SimpleGate
- Inherits:
-
Object
- Object
- SimpleGate
- Defined in:
- lib/simple_gate.rb
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ SimpleGate
constructor
Initialize a new SimpleGate.
-
#through(*gateways) {|gateway| ... } ⇒ Object
Establish a series of gateways and yields the last one created.
-
#through_to(*gateways) {|session| ... } ⇒ Object
Connect through a list of gateways to a target server.
-
#verbose? ⇒ Boolean
Is the verbose option turned on?.
Constructor Details
#initialize(options = {}) ⇒ SimpleGate
Initialize a new SimpleGate
10 11 12 13 14 |
# File 'lib/simple_gate.rb', line 10 def initialize(={}) @options = { :verbose => false }.merge() end |
Instance Method Details
#through(*gateways) {|gateway| ... } ⇒ Object
Establish a series of gateways and yields the last one created. Will automatically shut down gateway connections when the block closes.
Most of the code was taken from Capistrano and then changed to work outside of Capistrano.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/simple_gate.rb', line 58 def through(*gateways) Thread.abort_on_exception = true open_connections = [] gateways = gateways.flatten.collect { |g| ServerDefinition.find(g) } raise ArgumentError.new("No target chosen") if gateways.size == 0 tunnel = gateways[0].connection_info do |host, user, | STDERR.puts "Setting up tunnel #{gateways[0]}" if verbose? gw = Net::SSH::Gateway.new(host, user, ) open_connections << gw gw end gateway = (gateways[1..-1]).inject(tunnel) do |tunnel, destination| STDERR.puts "Connecting to #{destination}" if verbose? tunnel_port = tunnel.open(destination.host, (destination.port || 22)) = {:user => destination.user, :port => tunnel_port, :password => destination.password} local_host = ServerDefinition.new("127.0.0.1", ) local_host.connection_info do |host, user, | STDERR.puts "Connecting using local info #{local_host}" if verbose? gw = Net::SSH::Gateway.new(host, user, ) open_connections << gw gw end end yield(gateway) ensure while g = open_connections.pop g.shutdown! end end |
#through_to(*gateways) {|session| ... } ⇒ Object
Connect through a list of gateways to a target server. Treats the last ‘gateway’ as the target server and the others as gateways.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/simple_gate.rb', line 27 def through_to(*gateways) gateways = gateways.flatten raise ArgumentError.new("No target chosen") if gateways.size == 0 target = ServerDefinition.find(gateways.pop) if gateways.size == 0 target.connection_info do |host, user, | Net::SSH.start(host,user,) do |session| yield(session) end end return end through(gateways) do |gate| target.connection_info do |host, user, | gate.ssh(host, user, ) do |session| yield(session) end end end nil end |
#verbose? ⇒ Boolean
Is the verbose option turned on?
17 18 19 |
# File 'lib/simple_gate.rb', line 17 def verbose? @options[:verbose] end |