Class: SSH

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

Overview

Run SSH commands remotely on a server.

Instance Method Summary collapse

Constructor Details

#initialize(username, host, password = nil) ⇒ SSH

Returns a new instance of SSH.



7
8
9
10
11
# File 'lib/command/ssh/ssh.rb', line 7

def initialize(username, host, password = nil)
  @username = username
  @host = host
  @password = password
end

Instance Method Details

#run(command) ⇒ Object

Run the SSH command on the server



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
# File 'lib/command/ssh/ssh.rb', line 14

def run(command)
  Net::SSH.start(@host, @username, password: @password) do |ssh|
    output = ''
    exit_code = nil
    ssh.open_channel do |channel|
      channel.exec(command) do |_ch, success|
        abort "FAILED: Couldn't execute command #{command}" unless success

        channel.on_data do |_ch, data|
          puts data
          output += data
        end

        channel.on_extended_data do |_ch, _type, data|
          puts data
          output += data
        end

        channel.on_request('exit-status') { |_ch, data| exit_code = data.read_long }
      end
    end
    ssh.loop
    return { output: output, result: exit_code <= 0 }
  end
end