Class: Capistrano::SSH

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

Overview

A helper class for dealing with SSH connections.

Class Method Summary collapse

Class Method Details

.connect(server, config, port = 22, &block) ⇒ Object

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.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/capistrano/ssh.rb', line 21

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)
                    
    user, server_stripped, port = parse_server(server)         
    ssh_options[:username] = user if user   
    ssh_options[:port] = port if port
    
    Net::SSH.start(server_stripped,ssh_options,&block)
  rescue Net::SSH::AuthenticationFailed
    raise if methods.empty?
    password_value = config.password
    retry
  end
end

.parse_server(server) ⇒ Object

This regex is used for its byproducts, the $1-9 match vars. This regex will always match the ssh hostname and if there is a username or port they will be matched as well. This allows us to set the username and ssh port right in the server string: “[email protected]:8088” This remains fully backwards compatible and can still be intermixed with the old way of doing things. usernames and ports will be used from the server string if present but they will fall back to the regular defaults when not present. Returns and array like:

‘bob’, ‘demo.server.com’, ‘8088’

will always at least return the server:

nil, ‘demo.server.com’, nil


56
57
58
59
# File 'lib/capistrano/ssh.rb', line 56

def self.parse_server(server)
  server =~ /^(?:([^;,:=]+)@|)(.*?)(?::(\d+)|)$/
  [$1, $2, $3]
end