Class: AWSMine::SSHHelper

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

Overview

Main wrapper for SSH commands

Instance Method Summary collapse

Constructor Details

#initializeSSHHelper

Returns a new instance of SSHHelper.



7
8
9
10
11
# File 'lib/aws_minecraft/ssh_helper.rb', line 7

def initialize
  config = MineConfig.new
  @logger = Logger.new($stdout)
  @logger.level = Logger.const_get(config.loglevel)
end

Instance Method Details

#attach_to_server(ip) ⇒ Object



13
14
15
# File 'lib/aws_minecraft/ssh_helper.rb', line 13

def attach_to_server(ip)
  exec("ssh ec2-user@#{ip} -t 'cd /home/ec2-user && ./tmux-2.2/tmux attach -t #{AWSMine::MINECRAFT_SESSION_NAME}'")
end

#remote_exec(host, cmd) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/aws_minecraft/ssh_helper.rb', line 21

def remote_exec(host, cmd)
  @logger.debug("Executing '#{cmd}' on '#{host}'.")
  # This should work if ssh key is loaded and AgentFrowarding is set to yes.
  Net::SSH.start(host, 'ec2-user', config: true) do |ssh|
    output = ssh.exec!(cmd)
    @logger.info output
  end
end

#ssh(ip) ⇒ Object



17
18
19
# File 'lib/aws_minecraft/ssh_helper.rb', line 17

def ssh(ip)
  exec("ssh ec2-user@#{ip}")
end

#stop_server(host) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/aws_minecraft/ssh_helper.rb', line 30

def stop_server(host)
  Net::SSH.start(host, 'ec2-user', config: true) do |ssh|
    @logger.info('Opening channel to host.')
    channel = ssh.open_channel do |ch|
      @logger.info('Channel opened. Opening pty.')
      ch.request_pty do |c, success|
        raise 'Failed to request channel' unless success

        c.on_data do |_, data|
          puts "Received data: #{data}."
        end
        c.exec("cd /home/ec2-user && ./tmux-2.2/tmux attach -t #{AWSMine::MINECRAFT_SESSION_NAME}")
        @logger.info('Sending stop signal...')
        c.send_data("stop\n")
      end
    end
    channel.wait
  end
end