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



15
16
17
18
19
20
21
# File 'lib/aspera/ssh.rb', line 15

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

Instance Method Details

#execute(cmd, input = nil) ⇒ Object



23
24
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
# File 'lib/aspera/ssh.rb', line 23

def execute(cmd,input=nil)
  if cmd.is_a?(Array)
    # concatenate arguments, enclose in double quotes
    cmd=cmd.map{|v|'"'+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 << data}
      # prepare stderr processing, stderr if type = 1
      channel.on_extended_data do |chan, type, data|
        errormsg="#{cmd}: [#{data.chomp}]"
        # Happens when windows user hasn't logged in and created home account.
        if data.include?("Could not chdir to home directory")
          errormsg=errormsg+"\nHint: home not created in Windows?"
        end
        raise errormsg
      end
      channel.exec(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 # session
  return response
end