Class: MarhanCli::RemoteMachine

Inherits:
Object
  • Object
show all
Defined in:
lib/marhan_cli/network/errors.rb,
lib/marhan_cli/network/remote_machine.rb

Defined Under Namespace

Classes: RemoteMachineError

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ RemoteMachine

Returns a new instance of RemoteMachine.



7
8
9
10
11
12
# File 'lib/marhan_cli/network/remote_machine.rb', line 7

def initialize(host, port)
  Constraint.not_nil!(host, "host")
  Constraint.not_nil!(port, "port")
  @host = host
  @port = port
end

Instance Method Details

#add_id_to_authorized_keys(user, password, id_file) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/marhan_cli/network/remote_machine.rb', line 14

def add_id_to_authorized_keys(user, password, id_file)
  Constraint.not_nil!(user, "user")
  Constraint.not_nil!(password, "password")
  Constraint.not_nil!(id_file, "id_file")

  id_pub_content = File.read File.expand_path(id_file)
  id_pub_content = id_pub_content.chomp

  Net::SSH.start(@host, user, {:port => @port, :password => password}) do |ssh|
    stderr = ""
    ssh.exec!("echo '#{id_pub_content}' >> ~/.ssh/authorized_keys") do |channel, stream, data|
      stderr << data if stream == :stderr
    end

    raise RemoteMachineError, "#{stderr}" unless stderr.empty?
  end
end

#exec_remote_command(user, remote_command) ⇒ Object



56
57
58
59
60
61
62
63
64
# File 'lib/marhan_cli/network/remote_machine.rb', line 56

def exec_remote_command(user, remote_command)
  Net::SSH.start(@host, user, :port => @port) do |ssh|
    stderr = ""
    ssh.exec!(remote_command) do |channel, stream, data|
      stderr << data if stream == :stderr
    end
    raise RemoteMachineError, "#{stderr}" unless stderr.empty?
  end
end

#ssh_server_running?(user) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
54
# File 'lib/marhan_cli/network/remote_machine.rb', line 51

def ssh_server_running?(user)
  status = wait_for_ssh_server_status(user)
  status.match(%r{ssh start/running.+})
end

#wait_for_ssh_server_status(user) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/marhan_cli/network/remote_machine.rb', line 32

def wait_for_ssh_server_status(user)
  Net::SSH.start(@home, user, :port => @port) do |ssh|
    status = "";
    channel = ssh.open_channel do |ch|
      ch.exec "status ssh" do |ch, success|
        raise "could not execute command" unless success
        ch.on_data do |c, data|
          status << data
        end
        ch.on_extended_data do |c, type, data|
          $STDERR.print data
        end
      end
    end
    channel.wait
    return status
  end
end