Class: Mimas::SSH::Session

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

Defined Under Namespace

Classes: NonZeroExitCode

Instance Method Summary collapse

Constructor Details

#initialize(server, user:) ⇒ Session

Returns a new instance of Session.



21
22
23
24
# File 'lib/mimas/ssh.rb', line 21

def initialize(server, user:)
  @server = server
  @user = user || server.user
end

Instance Method Details

#perform(&block) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/mimas/ssh.rb', line 26

def perform(&block)
  @ssh = Net::SSH.start(@server.host, @user, timeout: 60, **@server.ssh_options)
  @hostname = run("cat /etc/hostname", capture: true).chomp
  yield(self)
ensure
  @ssh&.close
end

#run(command, capture: false, silent: false) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mimas/ssh.rb', line 34

def run(command, capture: false, silent: false)
  status = {}
  output = ""
  @ssh.exec!(command, status: status) do |channel, stream, data|
    if capture
      output << data
    elsif stream == :stderr
      print "#{data}".bold.red
    else
      print "#{data}".white
    end
  end

  if status[:exit_code] != 0 && !silent
    raise NonZeroExitCode.new(command: command, exit_code: status[:exit_code], output: output)
  end

  return output if capture
end

#script(name, sudo: false, vars: {}) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/mimas/ssh.rb', line 58

def script(name, sudo: false, vars: {})
  filename = "#{name}.sh"
  remote_location = "/tmp/#{filename}"

  source_path = File.expand_path("./scripts/#{filename}", __dir__)
  upload source_path, remote_location
  run "chmod +x #{remote_location}"

  vars = vars.to_a.map { it.join("=") }.join(" ")

  exec_command = remote_location
  exec_command = "#{vars} #{exec_command}".strip
  exec_command = "sudo #{exec_command}" if sudo

  run exec_command

  run "rm #{remote_location}"
end

#upload(source_file, destination_file) ⇒ Object



54
55
56
# File 'lib/mimas/ssh.rb', line 54

def upload(source_file, destination_file)
  @ssh.scp.upload! source_file, destination_file
end