Class: Tunneler::Ssh

Inherits:
Object
  • Object
show all
Defined in:
lib/tunneler/ssh.rb

Direct Known Subclasses

Tunneler::SshTunnel::Remote

Constant Summary collapse

SSH_READY_TIMEOUT =
70
SSH_CONNECTIVITY_TIMEOUT =
15
ACCEPTABLE_CONNECTIVITY_ERRORS =
[Errno::ECONNREFUSED]
SSH_COMMAND_TIMEOUT =
300
SCP_OPTIONS =
{ :recursive => true, :compression => "zlib" }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(user, host, options = {}) ⇒ Ssh

Returns a new instance of Ssh.



12
13
14
15
16
# File 'lib/tunneler/ssh.rb', line 12

def initialize(user, host, options={})
  @user = user
  @host = host
  @options = self.class.merge_options(options)
end

Class Method Details

.default_optionsObject



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

def self.default_options
  {
    :paranoid => false,
    :keys => [DEFAULT_SSH_KEY_PATH],
    :timeout => self::SSH_COMMAND_TIMEOUT,
  }
end

.merge_options(options = {}) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/tunneler/ssh.rb', line 26

def self.merge_options(options={})
  if options.empty?
    Ssh.default_options
  else
    Ssh.default_options.merge(options)
  end
end

Instance Method Details

#scp(local_path, remote_path) ⇒ Object



78
79
80
81
82
# File 'lib/tunneler/ssh.rb', line 78

def scp(local_path, remote_path)
  Net::SSH.start(@host, @user, @options) do |ssh|
    ssh.scp.upload!(local_path, remote_path, SCP_OPTIONS)
  end
end

#ssh(command, options_override = {}) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/tunneler/ssh.rb', line 65

def ssh(command, options_override={})
  if options_override.empty?
    options = @options
  else
    options = options_override
  end
  output = ""
  Net::SSH.start(@host, @user, @options) do |ssh|
    output = ssh.exec!(command)
  end
  output
end

#sshable?Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/tunneler/ssh.rb', line 43

def sshable?
  begin
    return test_connectivity
  rescue Exception => e
    if ACCEPTABLE_CONNECTIVITY_ERRORS.include?(e.class)
      Tunneler.log "Connectivity error: #{e.class} - #{e.message}", :debug
      return false
    else
      raise e
    end
  end
end

#test_connectivityObject



56
57
58
59
60
61
62
63
# File 'lib/tunneler/ssh.rb', line 56

def test_connectivity
  options_override = @options.clone
  options_override[:timeout] = self.class::SSH_CONNECTIVITY_TIMEOUT
  options_override[:verbose] = :debug if Tunneler.debug
  if ssh("whoami", options_override).strip == @user
    return true
  end
end

#wait_for_ssh_accessObject



34
35
36
37
38
39
40
41
# File 'lib/tunneler/ssh.rb', line 34

def wait_for_ssh_access
  Timer.timeout("#{@host}: SSH test",self.class::SSH_READY_TIMEOUT) do
    until sshable? do
      Tunneler.log "Waiting between connection attempts", :debug
      sleep 5
    end
  end
end