Sha256: 04db76662a121c86d8614df70187427de7610f40c309f9cf8d3c9c12555933e5

Contents?: true

Size: 1.34 KB

Versions: 71

Compression:

Stored size: 1.34 KB

Contents

require 'net/ssh'

class KuberKit::Shell::SshSession
  SshSessionError = Class.new(KuberKit::Error)

  attr_reader :session, :host, :user, :port

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

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

  def exec!(command)
    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
        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
end

Version data entries

71 entries across 71 versions & 1 rubygems

Version Path
kuber_kit-0.5.0 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.9 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.8 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.7 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.6 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.5 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.4 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.3 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.2 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.1 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.4.0 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.3.11 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.3.10 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.3.9 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.3.8 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.3.7 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.3.6 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.3.5 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.3.4 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-0.3.3 lib/kuber_kit/shell/ssh_session.rb