/
ssh.rb
39 lines (36 loc) · 1.41 KB
/
ssh.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require 'net/ssh'
module SwitchTower
unless ENV['SKIP_VERSION_CHECK']
require 'switchtower/version'
require 'net/ssh/version'
ssh_version = [Net::SSH::Version::MAJOR, Net::SSH::Version::MINOR, Net::SSH::Version::TINY]
required_version = [1,0,5]
if !Version.check(required_version, ssh_version)
raise "You have Net::SSH #{ssh_version.join(".")}, but you need at least #{required_version.join(".")}"
end
end
# A helper class for dealing with SSH connections.
class SSH
# An abstraction to make it possible to connect to the server via public key
# without prompting for the password. If the public key authentication fails
# this will fall back to password authentication.
#
# If a block is given, the new session is yielded to it, otherwise the new
# session is returned.
def self.connect(server, config, port=22, &block)
methods = [ %w(publickey hostbased), %w(password keyboard-interactive) ]
password_value = nil
begin
ssh_options = { :username => config.user,
:password => password_value,
:port => port,
:auth_methods => methods.shift }.merge(config.ssh_options)
Net::SSH.start(server,ssh_options,&block)
rescue Net::SSH::AuthenticationFailed
raise if methods.empty?
password_value = config.password
retry
end
end
end
end