Class: Knj::SSHRobot

Inherits:
Object show all
Defined in:
lib/knj/sshrobot/sshrobot.rb

Defined Under Namespace

Classes: Forward

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ SSHRobot

Returns a new instance of SSHRobot.



2
3
4
5
6
7
8
# File 'lib/knj/sshrobot/sshrobot.rb', line 2

def initialize(args)
  require "net/ssh"
  
  @forwards = []
  @args = Knj::ArrayExt.hash_sym(args)
  @args[:port] = 22 if !@args.key?(:port)
end

Instance Method Details

#closeObject



71
72
73
74
# File 'lib/knj/sshrobot/sshrobot.rb', line 71

def close
  @session.close if @session
  @session = nil
end

#exec(command) ⇒ Object Also known as: shellCMD



27
28
29
# File 'lib/knj/sshrobot/sshrobot.rb', line 27

def exec(command)
  return self.session.exec!(command)
end

#fileExists(filepath) ⇒ Object



53
54
55
56
57
# File 'lib/knj/sshrobot/sshrobot.rb', line 53

def fileExists(filepath)
  result = self.exec("ls #{Strings.UnixSafe(filepath)}").strip
  return true if result == filepath
  return false
end

#forward(args) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/knj/sshrobot/sshrobot.rb', line 59

def forward(args)
  Knj::ArrayExt.hash_sym(args)
  args[:type] = "local" if !args[:type]
  args[:session] = self.session_spawn if !args[:session]
  args[:host_local] = "0.0.0.0" if !args[:host_local]
  return SSHRobot::Forward.new(args)
end

#sessionObject



10
11
12
13
# File 'lib/knj/sshrobot/sshrobot.rb', line 10

def session
  @session = self.session_spawn if !@session
  return @session
end

#session_spawnObject



15
16
17
# File 'lib/knj/sshrobot/sshrobot.rb', line 15

def session_spawn
  return Net::SSH.start(@args[:host], @args[:user], :password => @args[:passwd], :port => @args[:port].to_i)
end

#sftpObject Also known as: getSFTP



23
24
25
# File 'lib/knj/sshrobot/sshrobot.rb', line 23

def sftp
  @sftp = Net::SFTP.start(@args[:host], @args[:user], @args[:passwd], :port => @args[:port].to_i)
end

#shellObject Also known as: getShell



19
20
21
# File 'lib/knj/sshrobot/sshrobot.rb', line 19

def shell
  return self.session.shell.sync
end

#sudo_exec(sudo_passwd, command) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/knj/sshrobot/sshrobot.rb', line 31

def sudo_exec(sudo_passwd, command)
  result = ""
  
  self.session.open_channel do |ch|
    ch.request_pty
    
    ch.exec("sudo #{command}") do |ch, success|
      ch.on_data do |ch, data|
        if data =~ /^\[sudo\] password for (.+):\s*$/
          ch.send_data("#{sudo_passwd}\n")
        else
          result << data
        end
      end
    end
  end
  
  self.session.loop
  
  return result
end