Class: Aspera::Ssh

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/ssh.rb

Overview

A simple wrapper around Net::SSH executes one command and get its result from stdout

Instance Method Summary collapse

Constructor Details

#initialize(host, username, ssh_options) ⇒ Ssh

ssh_options: same as Net::SSH.start see: net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start



28
29
30
31
32
33
34
35
# File 'lib/aspera/ssh.rb', line 28

def initialize(host, username, ssh_options)
  Log.log.debug{"ssh:#{username}@#{host}"}
  Log.log.debug{"ssh_options:#{ssh_options}"}
  @host = host
  @username = username
  @ssh_options = ssh_options
  @ssh_options[:logger] = Log.log
end

Instance Method Details

#execute(cmd, input = nil) ⇒ Object



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
66
67
# File 'lib/aspera/ssh.rb', line 37

def execute(cmd, input=nil)
  if cmd.is_a?(Array)
    # concatenate arguments, enclose in double quotes
    cmd = cmd.map{|v|%Q("#{v}")}.join(' ')
  end
  Log.log.debug{"cmd=#{cmd}"}
  response = []
  Net::SSH.start(@host, @username, @ssh_options) do |session|
    ssh_channel = session.open_channel do |channel|
      # prepare stdout processing
      channel.on_data{|_chan, data|response.push(data)}
      # prepare stderr processing, stderr if type = 1
      channel.on_extended_data do |_chan, _type, data|
        error_message = "#{cmd}: [#{data.chomp}]"
        # Happens when windows user hasn't logged in and created home account.
        if data.include?('Could not chdir to home directory')
          error_message += "\nHint: home not created in Windows?"
        end
        raise error_message
      end
      # send command to SSH channel (execute) cspell: disable-next-line
      channel.send('cexe'.reverse, cmd){|_ch, _success|channel.send_data(input) unless input.nil?}
    end
    # wait for channel to finish (command exit)
    ssh_channel.wait
    # main ssh session loop
    session.loop
  end
  # response as single string
  return response.join
end