Class: KuberKit::Shell::SshSession

Inherits:
Object
  • Object
show all
Defined in:
lib/kuber_kit/shell/ssh_session.rb

Constant Summary collapse

SshSessionError =
Class.new(KuberKit::Error)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host:, user:, port:) ⇒ SshSession

Returns a new instance of SshSession.



8
9
10
11
12
13
# File 'lib/kuber_kit/shell/ssh_session.rb', line 8

def initialize(host:, user:, port:)
  @host = host
  @user = user
  @port = port
  @session = Net::SSH.start(host, user, {port: port})
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



6
7
8
# File 'lib/kuber_kit/shell/ssh_session.rb', line 6

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



6
7
8
# File 'lib/kuber_kit/shell/ssh_session.rb', line 6

def port
  @port
end

#sessionObject (readonly)

Returns the value of attribute session.



6
7
8
# File 'lib/kuber_kit/shell/ssh_session.rb', line 6

def session
  @session
end

#userObject (readonly)

Returns the value of attribute user.



6
7
8
# File 'lib/kuber_kit/shell/ssh_session.rb', line 6

def user
  @user
end

Instance Method Details

#connected?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/kuber_kit/shell/ssh_session.rb', line 15

def connected?
  !!@session
end

#disconnectObject



19
20
21
22
23
# File 'lib/kuber_kit/shell/ssh_session.rb', line 19

def disconnect
  return unless connected?
  @session.close
  @session = nil
end

#exec!(command, merge_stderr: false) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/kuber_kit/shell/ssh_session.rb', line 25

def exec!(command, merge_stderr: false)
  stdout_data = ''
  stderr_data = ''
  exit_code = nil
  channel = session.open_channel do |ch|
    ch.exec(command) do |ch, success|
      if !success
        raise SshSessionError, "Shell command failed: #{command}\r\n#{stdout_data}\r\n#{stderr_data}"
      end

      channel.on_data do |ch,data|
        stdout_data += data
      end

      channel.on_extended_data do |ch,type,data|
        stderr_data += data
        
        if merge_stderr
          stdout_data += data
        end
      end

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

  channel.wait
  session.loop

  stdout_data = stdout_data.chomp.strip

  if exit_code != 0
    raise SshSessionError, "Shell command failed: #{command}\r\n#{stdout_data}\r\n#{stderr_data}"
  end

  stdout_data
rescue Net::SSH::Exception => e
  raise SshSessionError, "Shell command failed: #{command}\r\n#{e.message}"
end