Class: KuberKit::Shell::SshSession
- Defined in:
- lib/kuber_kit/shell/ssh_session.rb
Constant Summary collapse
Instance Attribute Summary collapse
-
#host ⇒ Object
readonly
Returns the value of attribute host.
-
#port ⇒ Object
readonly
Returns the value of attribute port.
-
#session ⇒ Object
readonly
Returns the value of attribute session.
-
#user ⇒ Object
readonly
Returns the value of attribute user.
Instance Method Summary collapse
- #connected? ⇒ Boolean
- #disconnect ⇒ Object
- #exec!(command, merge_stderr: false) ⇒ Object
-
#initialize(host:, user:, port:) ⇒ SshSession
constructor
A new instance of SshSession.
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
#host ⇒ Object (readonly)
Returns the value of attribute host.
6 7 8 |
# File 'lib/kuber_kit/shell/ssh_session.rb', line 6 def host @host end |
#port ⇒ Object (readonly)
Returns the value of attribute port.
6 7 8 |
# File 'lib/kuber_kit/shell/ssh_session.rb', line 6 def port @port end |
#session ⇒ Object (readonly)
Returns the value of attribute session.
6 7 8 |
# File 'lib/kuber_kit/shell/ssh_session.rb', line 6 def session @session end |
#user ⇒ Object (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
15 16 17 |
# File 'lib/kuber_kit/shell/ssh_session.rb', line 15 def connected? !!@session end |
#disconnect ⇒ Object
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.}" end |