Class: Traquitana::SSH

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, user, options = nil) ⇒ SSH

Returns a new instance of SSH.



9
10
11
12
13
14
15
# File 'lib/ssh.rb', line 9

def initialize(host, user, options = nil)
   @host    = host
   @user    = user
   @options = options || {}
   @options[:verbose] = :error
   STDOUT.puts "Connecting to \e[1m#{@host}\e[0m using user \e[1m#{@user}\e[0m"
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



7
8
9
# File 'lib/ssh.rb', line 7

def host
  @host
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/ssh.rb', line 7

def options
  @options
end

#userObject (readonly)

Returns the value of attribute user.



7
8
9
# File 'lib/ssh.rb', line 7

def user
  @user
end

Instance Method Details

#execute(cmds, verbose = false) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ssh.rb', line 17

def execute(cmds,verbose=false)
  rst = []

  Net::SSH.start(@host,@user,@options) do |ssh|
    ssh.open_channel do |channel|
      channel.request_pty do |ch, success|
        raise "Can't get PTY" unless success
        for cmd in cmds
          STDOUT.puts "Executing #{cmd} on remote host ..." if verbose
          rst << ch.exec(cmd)
        end # for

        ch.on_data do |chd, data|
          msg = data.inspect.to_s.gsub(/^"/,"").gsub(/"$/,"").gsub(/"\\"/,"\\").gsub("\\r","").gsub("\\n","\n").gsub("\\e","\e").strip.chomp
          if data.inspect =~ /sudo/
            pwd = ask("\nNeed password to run as root/sudo: ") { |c| c.echo = "*" }
            channel.send_data("#{pwd}\n")
            sleep 0.1
          else
            STDOUT.puts msg if msg.size > 1
          end
          chd.wait
        end
      end # tty
    end # channel
    ssh.loop
  end # ssh start
  rst
end

#send_files(col, updater = nil) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ssh.rb', line 47

def send_files(col,updater=nil)
  Net::SCP.start(@host, @user, @options) do |scp|
      for files in col
         from, to = *files
         next if from.nil? || to.nil?
         scp.upload!(from,to) do |ch, name, sent, total|
            if !updater.nil?
               updater.name  = to
               updater.total = total
               updater.update(sent)
            end
         end
         updater.reset if !updater.nil?
      end
   end
end