Class: KnifeSolo::SshConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/knife-solo/ssh_connection.rb

Defined Under Namespace

Classes: ExecResult

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, user, connection_options, sudo_password_hook) ⇒ SshConnection

Returns a new instance of SshConnection.



26
27
28
29
30
31
# File 'lib/knife-solo/ssh_connection.rb', line 26

def initialize(host, user, connection_options, sudo_password_hook)
  @host = host
  @user = user
  @connection_options = connection_options
  @password_hook = sudo_password_hook
end

Instance Attribute Details

#connection_optionsObject (readonly)

Returns the value of attribute connection_options.



33
34
35
# File 'lib/knife-solo/ssh_connection.rb', line 33

def connection_options
  @connection_options
end

#hostObject (readonly)

Returns the value of attribute host.



33
34
35
# File 'lib/knife-solo/ssh_connection.rb', line 33

def host
  @host
end

#userObject (readonly)

Returns the value of attribute user.



33
34
35
# File 'lib/knife-solo/ssh_connection.rb', line 33

def user
  @user
end

Instance Method Details

#passwordObject



47
48
49
# File 'lib/knife-solo/ssh_connection.rb', line 47

def password
  @password ||= @password_hook.call
end

#run_command(command, output = nil) ⇒ Object



51
52
53
54
55
56
57
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
# File 'lib/knife-solo/ssh_connection.rb', line 51

def run_command(command, output = nil)
  result = ExecResult.new

  session.open_channel do |channel|
    channel.request_pty
    channel.exec(command) do |_, success|
      raise "ssh.channel.exec failure" unless success

      channel.on_data do |ch, data|  # stdout
        if data =~ /^knife sudo password: /
          ch.send_data("#{password}\n")
        else
          Chef::Log.debug("#{command} stdout: #{data}")
          output << data if output
          result.stdout << data
        end
      end

      channel.on_extended_data do |ch, type, data|
        next unless type == 1
        Chef::Log.debug("#{command} stderr: #{data}")
        output << data if output
        result.stderr << data
      end

      channel.on_request("exit-status") do |ch, data|
        result.exit_code = data.read_long
      end

    end
  end.wait

  result
end

#session(&block) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/knife-solo/ssh_connection.rb', line 35

def session(&block)
  @session ||= begin
    if connection_options[:gateway]
      co = connection_options
      gw_user,gw =  co.delete(:gateway).split '@'
      Net::SSH::Gateway.new(gw, gw_user).ssh(host, user, co, &block)
    else
      Net::SSH.start(host, user, connection_options, &block)
    end
  end
end