Class: CopySSH

Inherits:
ExecuteBase show all
Defined in:
lib/teuton/case/execute/copy_ssh.rb

Instance Method Summary collapse

Methods inherited from ExecuteBase

#initialize

Methods included from Verbose

#verbose, #verboseln

Constructor Details

This class inherits a constructor from ExecuteBase

Instance Method Details

#call(host, localfilename) ⇒ Object



9
10
11
12
13
14
15
16
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
46
47
# File 'lib/teuton/case/execute/copy_ssh.rb', line 9

def call(host, localfilename)
  # Check params
  unless config.get("#{host}_route".to_sym) == "NODATA"
    log("'copy script' requires direct host access!", :error)
    return false
  end

  host = host.to_s

  begin
    if sessions[host].nil?
      # Open new SSH session
      ip = config.get("#{host}_ip".to_sym).to_s
      username = config.get("#{host}_username".to_sym).to_s
      password = config.get("#{host}_password".to_sym).to_s
      port = config.get("#{host}_port".to_sym).to_i
      port = 22 if port.zero?

      sessions[host] = Net::SSH.start(
        ip,
        username,
        port: port,
        password: password,
        keepalive: true,
        timeout: 30,
        non_interactive: true
      )
    end
    if sessions[host].instance_of? Net::SSH::Connection::Session
      copy_to(host, localfilename)
    else
      "SSH: NO CONNECTION!"
    end
  rescue => e
    sessions[host] = :nosession
    conn_status[host] = :error
    log("[#{e.class}] SSH on <#{username}@#{ip}>", :error)
  end
end

#copy_to(host, localfilename) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/teuton/case/execute/copy_ssh.rb', line 49

def copy_to(host, localfilename)
  ip = get((host + "_ip").to_sym)
  username = get((host + "_username").to_sym).to_s
  password = get((host + "_password").to_sym).to_s
  port = get((host + "_port").to_sym).to_i
  port = 22 if port.zero?

  localfilepath = File.join(Dir.pwd, localfilename)
  remotefilepath = File.join(".", File.basename(localfilename))

  # Upload a file or directory to the remote host
  begin
    Net::SFTP.start(ip, username, password: password, port: port) do |sftp|
      sftp.upload!(localfilepath, remotefilepath)
    end
  rescue
    log("copy file: #{localfilename} => #{remotefilepath}", :error)
    return false
  end
  true
end