Class: VagrantSsh::Shell

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-ssh/shell.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hostname, logger: Logger.new(STDOUT), options: {}) ⇒ Shell

Returns a new instance of Shell.



5
6
7
8
9
10
11
# File 'lib/vagrant-ssh/shell.rb', line 5

def initialize(hostname, logger: Logger.new(STDOUT), options: {})
  @options  = { user:     'vagrant',
                password: 'vagrant' }.merge(options)
  @user     = @options[:user]
  @hostname = hostname
  @logger   = logger # left out of options so it does not conflict with Net::SSH own options hash
end

Instance Attribute Details

#exit_codeObject (readonly)

Returns the value of attribute exit_code.



3
4
5
# File 'lib/vagrant-ssh/shell.rb', line 3

def exit_code
  @exit_code
end

#exit_signalObject (readonly)

Returns the value of attribute exit_signal.



3
4
5
# File 'lib/vagrant-ssh/shell.rb', line 3

def exit_signal
  @exit_signal
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/vagrant-ssh/shell.rb', line 3

def options
  @options
end

Instance Method Details

#execute(command) ⇒ Object



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
40
41
# File 'lib/vagrant-ssh/shell.rb', line 13

def execute(command)
  ssh = Net::SSH.start(@hostname, @user, @options)
  @logger.info "Executing SSH command: #{command}"
  stdout      = ''
  stderr      = ''
  @exit_code   = nil
  @exit_signal = nil
  ssh.open_channel do |channel|
    channel.exec(command) do |_ch, success|
      abort "FAILED: couldn't execute command: (#{command})" unless success
      channel.on_data { |_ch, data| stdout += data }
      channel.on_extended_data { |_ch, _type, data| stderr += data }
      channel.on_request('exit-status') { |_ch, data| @exit_code = data.read_long }
      channel.on_request('exit-signal') { |_ch, data| @exit_signal = data.read_long }
    end
  end
  ssh.loop

  if stderr.size > 0
    @logger.error "#{@exit_code} #{stderr}"
  elsif @exit_code != 0
    @logger.info "SSH Completed with non-zero exit code '#{@exit_code}'"
  end
  if stdout.size > 0
    @logger.info "#{stdout}"
  end

  stdout # TODO: return everything instead of just stdout
end