Sha256: 915f7f6d9a04bb8656c2a6da0c0b99641fbddae3b21c2b6601a035392f23fde4

Contents?: true

Size: 1.45 KB

Versions: 21

Compression:

Stored size: 1.45 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, 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
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
kuber_kit-1.3.8 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.3.7 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.1.8 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.3.6 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.1.7 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.3.5 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.3.4 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.1.6 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.3.3 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.3.2 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.1.5 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.3.1 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.3.0 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.1.4 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.2.7 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.2.6 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.2.5 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.2.4 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.2.2 lib/kuber_kit/shell/ssh_session.rb
kuber_kit-1.1.2 lib/kuber_kit/shell/ssh_session.rb