Class: Prof::SshGateway

Inherits:
Object
  • Object
show all
Defined in:
lib/prof/ssh_gateway.rb

Instance Method Summary collapse

Constructor Details

#initialize(gateway_host:, gateway_username:, gateway_password: nil, ssh_key: nil) ⇒ SshGateway

Returns a new instance of SshGateway.



18
19
20
21
22
23
24
# File 'lib/prof/ssh_gateway.rb', line 18

def initialize(gateway_host:, gateway_username:, gateway_password: nil, ssh_key: nil)
  @gateway_host     = gateway_host
  @gateway_username = gateway_username
  @gateway_password = gateway_password
  @ssh_key          = ssh_key
  @forwards         = {}
end

Instance Method Details

#execute_on(host, cmd, options = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/prof/ssh_gateway.rb', line 26

def execute_on(host, cmd, options = {})
  user           = options.fetch(:user, 'vcap')
  password       = options.fetch(:password, 'c1oudc0w')
  run_as_root    = options.fetch(:root, false)
  discard_stderr = options.fetch(:discard_stderr, false)

  cmd = "echo -e \"#{password}\\n\" | sudo -S #{cmd}" if run_as_root
  cmd << ' 2>/dev/null' if discard_stderr

  ssh_gateway_options = {
    password: password,
    paranoid: false
  }

  ssh_gateway_options[:key_data] = [@ssh_key] unless @ssh_key.nil?

  ssh_gateway.ssh(
    host,
    user,
    ssh_gateway_options,
  ) do |ssh|
    ssh.exec!(cmd)
  end
end

#scp_from(host, remote_path, local_path, options = {}) ⇒ Object



62
63
64
65
66
67
68
69
70
71
# File 'lib/prof/ssh_gateway.rb', line 62

def scp_from(host, remote_path, local_path, options = {})
  with_port_forwarded_to(host, 22) do |local_port|
    options[:port] = local_port
    options[:user] ||= 'vcap'
    options[:password] ||= 'c1oudc0w'
    Net::SCP.start('127.0.0.1', options.fetch(:user), options) do |scp|
      scp.download! remote_path, local_path
    end
  end
end

#scp_to(host, local_path, remote_path, options = {}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
# File 'lib/prof/ssh_gateway.rb', line 51

def scp_to(host, local_path, remote_path, options = {})
  with_port_forwarded_to(host, 22) do |local_port|
    options[:port] = local_port
    options[:user] ||= 'vcap'
    options[:password] ||= 'c1oudc0w'
    Net::SCP.start('127.0.0.1', options.fetch(:user), options) do |scp|
      scp.upload! local_path, remote_path
    end
  end
end

#with_port_forwarded_to(remote_host, remote_port, &block) ⇒ Object



73
74
75
# File 'lib/prof/ssh_gateway.rb', line 73

def with_port_forwarded_to(remote_host, remote_port, &block)
  ssh_gateway.open(remote_host, remote_port, &block)
end