Class: SSHake::Session

Inherits:
BaseSession show all
Defined in:
lib/sshake/session.rb

Instance Attribute Summary collapse

Attributes inherited from BaseSession

#id, #klogger, #raise_on_error

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, username = nil, **options) ⇒ Sshake::Session

Create a new SSH session



26
27
28
29
30
31
32
# File 'lib/sshake/session.rb', line 26

def initialize(host, username = nil, **options)
  super
  @host = host
  @username = username
  @session_options = options
  @session_options.delete(:klogger)
end

Instance Attribute Details

#hostString (readonly)

Return the host to connect to

Returns:

  • (String)


21
22
23
# File 'lib/sshake/session.rb', line 21

def host
  @host
end

#sessionNet::SSH::Session (readonly)

The underlying net/ssh session

Returns:

  • (Net::SSH::Session)


16
17
18
# File 'lib/sshake/session.rb', line 16

def session
  @session
end

Class Method Details

.create(*args) ⇒ Object



194
195
196
197
198
199
200
201
202
# File 'lib/sshake/session.rb', line 194

def create(*args)
  session = new(*args)

  if recorder = Thread.current[:sshake_recorder]
    return RecordedSession.new(recorder, session)
  end

  session
end

Instance Method Details

#connectvoid

This method returns an undefined value.

Connect to the SSH server



51
52
53
54
55
# File 'lib/sshake/session.rb', line 51

def connect
  klogger.debug 'Connecting', id: @id, host: @host, user: @user, port: @session_options[:port] || 22
  @session = Net::SSH.start(@host, user, **@session_options)
  true
end

#connected?Boolean

Is there an established SSH connection

Returns:

  • (Boolean)


60
61
62
# File 'lib/sshake/session.rb', line 60

def connected?
  !@session.nil?
end

#disconnectvoid

This method returns an undefined value.

Disconnect the underlying SSH connection



67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/sshake/session.rb', line 67

def disconnect
  return false if @session.nil?

  begin
    klogger.debug 'Closing connection', id: @id, host: @host
    @session.close
    klogger.debug 'Connection closed', id: @id, host: @host
  rescue StandardError => e
    logger.exception(e, 'Connection not closed')
    nil
  end
  @session = nil
  true
end

#execute(commands, options = nil, &block) ⇒ Object

rubocop:disable Metrics/AbcSize



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/sshake/session.rb', line 91

def execute(commands, options = nil, &block)
  options = create_options(options, block)
  command_to_execute = prepare_commands(commands, options)

  # Execute the command
  response = Response.new
  response.command = command_to_execute
  connect unless connected?

  klogger.group(id: @id, host: @host) do
    klogger.info 'Executing command', command: command_to_execute, timeout: options.timeout

    begin
      channel = nil

      Timeout.timeout(options.timeout) do
        channel = @session.open_channel do |ch|
          response.start_time = Time.now

          channel.exec(command_to_execute) do |_, success|
            raise "Command \"#{command_to_execute}\" was unable to execute" unless success

            ch.send_data(options.stdin) if options.stdin

            if options.file_to_stream.nil? && options.sudo_password.nil?
              klogger.debug 'Sending EOF to channel'
              ch.eof!
            end

            ch.on_data do |_, data|
              response.stdout += data
              options.stdout&.call(data)
              klogger.debug "[stdout] #{data.gsub(/\r/, '').strip}"
            end

            ch.on_extended_data do |_, _, data|
              response.stderr += data.delete("\r")
              options.stderr&.call(data)
              klogger.debug "[stderr] #{data.gsub(/\r/, '').strip}"
              if options.sudo_password && data =~ /^\[sshake-sudo-password\]:\s\z/
                klogger.debug 'Sending sudo password', length: options.sudo_password.length
                ch.send_data "#{options.sudo_password}\n"

                if options.file_to_stream.nil?
                  klogger.debug 'Sending EOF after password'
                  ch.eof!
                end
              end
            end

            ch.on_request('exit-status') do |_, data|
              response.exit_code = data.read_long&.to_i
              klogger.info 'Exited', exit_code: response.exit_code
            end

            ch.on_request('exit-signal') do |_, data|
              response.exit_signal = data.read_long
            end

            if options.file_to_stream
              ch.on_process do |_, data|
                next if ch.eof?

                if ch.output.length < 128 * 1024
                  if data = options.file_to_stream.read(1024 * 1024)
                    ch.send_data(data)
                    response.bytes_streamed += data.bytesize
                  else
                    ch.eof!
                  end
                end
              end
            end
          end
        end
        channel.wait
      end
    rescue Timeout::Error
      klogger.debug 'Command timed out'
      kill!
      response.timeout!
    ensure
      response.finish_time = Time.now
    end
  end

  handle_response(response, options)
end

#kill!Object

Kill the underlying connection



83
84
85
86
87
88
# File 'lib/sshake/session.rb', line 83

def kill!
  klogger.debug 'Attemping to shutdown', id: @id, host: @host
  @session.shutdown!
  klogger.debug 'Shutdown success', id: @id, host: @host
  @session = nil
end

#portInteger

Return the port that will be connected to

Returns:

  • (Integer)


44
45
46
# File 'lib/sshake/session.rb', line 44

def port
  @session_options[:port] || 22
end

#userString

Return the username for the connection

Returns:

  • (String)


37
38
39
# File 'lib/sshake/session.rb', line 37

def user
  @user || ENV.fetch('USER', nil)
end

#write_data(path, data, options = nil, &block) ⇒ Object

rubocop:enable Metrics/AbcSize



181
182
183
184
185
186
187
188
189
190
# File 'lib/sshake/session.rb', line 181

def write_data(path, data, options = nil, &block)
  connect unless connected?
  tmp_path = "/tmp/sshake-tmp-file-#{SecureRandom.hex(32)}"
  @session.sftp.file.open(tmp_path, 'w') do |f|
    d = data.dup.force_encoding('BINARY')
    f.write(d.slice!(0, 1024)) until d.empty?
  end
  response = execute("mv #{tmp_path} #{path}", options, &block)
  response.success?
end