class RemoteCommand

Attributes

capture_output[R]
host[R]
options[R]
output_stream[R]
simulate[R]
suppress_output[R]
user[R]

Public Class Methods

new(params) click to toggle source
# File lib/script_executor/remote_command.rb, line 8
def initialize(params)
  params = sanitize_parameters params

  @host = params.delete(:domain)
  @host = params.delete(:host) if host.nil? and params[:host]
  @user = params.delete(:user)

  @suppress_output = params.delete(:suppress_output)
  @capture_output = params.delete(:capture_output)
  @output_stream = params[:output_stream]
  @simulate = params.delete(:simulate)

  @options = params
end

Public Instance Methods

execute(commands, line_action) click to toggle source
# File lib/script_executor/remote_command.rb, line 23
def execute(commands, line_action)
  options[:password] = HighLine.new.ask("Enter password for #{user}: ") {|q| q.echo = '*'} if options[:password].nil?
  options[:user] = user

  print commands, $stdout

  unless simulate
    storage = capture_output ? OutputBuffer.new : nil
    output = if output_stream
               output_stream
             else
               suppress_output ? nil : $stdout
             end

    Net::SSH.start(host, user, options) do |session|
      session.exec(commands) do |channel, _, line|
        if ask_password?(line)
          channel.request_pty
          channel.send_data options[:password] + "\n"
        else
          if output
            output.write(line)
            output.flush
          end

          if storage
            storage.save(line.chomp)
          end

          line_action.call(line) if line_action
        end
      end

      session.loop # run the aggregated event loop
    end

    storage.buffer.join("\n") if storage
  end
end

Private Instance Methods

ask_password?(line) click to toggle source
# File lib/script_executor/remote_command.rb, line 105
def ask_password?(line)
  line =~ /^\[sudo\] password for user:/ || line =~ /sudo password:/ || line =~ /Password:/
end
permitted_params() click to toggle source
# File lib/script_executor/remote_command.rb, line 117
def permitted_params
  @permitted_params ||= [:script, :sudo, :remote, :line_action, :password,
                         :suppress_output, :capture_output, :output_stream, :simulate,
                         :domain, :host, :port, :user, :options]
end
print(commands, output) click to toggle source
sanitize_parameters(params) click to toggle source
# File lib/script_executor/remote_command.rb, line 109
def sanitize_parameters(params)
  params.each do |key, _|
    params.delete(key) unless permitted_params.include? key.to_sym
  end

  params
end
ssh_command(user, host, port, identity_file) click to toggle source
# File lib/script_executor/remote_command.rb, line 93
def ssh_command(user, host, port, identity_file)
  cmd = user ? host : "#{user}@#{host}"

  cmd << " -i #{identity_file}" if identity_file

  #cmd << " -p #{port}" if port

  #cmd << " -t -t"

  "ssh #{cmd}"
end