2011-12-18 01:16:11 +00:00
|
|
|
require 'optparse'
|
|
|
|
|
2010-08-25 06:46:10 +00:00
|
|
|
module Vagrant
|
|
|
|
module Command
|
2011-12-18 01:16:11 +00:00
|
|
|
class SSH < Base
|
2010-08-25 06:46:10 +00:00
|
|
|
def execute
|
2011-12-18 01:16:11 +00:00
|
|
|
options = {}
|
2010-08-25 06:46:10 +00:00
|
|
|
|
2011-12-18 01:16:11 +00:00
|
|
|
opts = OptionParser.new do |opts|
|
|
|
|
opts.banner = "Usage: vagrant ssh [vm-name] [-c command]"
|
2010-08-25 06:46:10 +00:00
|
|
|
|
2011-12-18 01:16:11 +00:00
|
|
|
opts.separator ""
|
|
|
|
|
|
|
|
opts.on("-c", "--command COMMAND", "Execute an SSH command directly.") do |c|
|
|
|
|
options[:command] = c
|
2010-08-25 06:46:10 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-12-18 01:16:11 +00:00
|
|
|
argv = parse_options(opts)
|
|
|
|
return if !argv
|
2010-08-25 06:46:10 +00:00
|
|
|
|
2011-12-18 01:16:11 +00:00
|
|
|
# SSH always requires a target VM
|
|
|
|
raise Errors::MultiVMTargetRequired, :command => "ssh" if @env.multivm? && !argv[0]
|
2011-08-29 03:38:56 +00:00
|
|
|
|
2011-12-18 01:16:11 +00:00
|
|
|
# Execute the actual SSH
|
|
|
|
with_target_vms(argv[0]) do |vm|
|
2011-08-29 03:38:56 +00:00
|
|
|
# Basic checks that are required for proper SSH
|
|
|
|
raise Errors::VMNotCreatedError if !vm.created?
|
2011-12-22 21:48:22 +00:00
|
|
|
raise Errors::VMInaccessible if !vm.state == :inaccessible
|
|
|
|
raise Errors::VMNotRunningError if vm.state != :running
|
2011-08-29 03:38:56 +00:00
|
|
|
|
2011-12-18 01:16:11 +00:00
|
|
|
if options[:command]
|
|
|
|
ssh_execute(vm, options[:command])
|
|
|
|
else
|
|
|
|
ssh_connect(vm)
|
|
|
|
end
|
2010-08-25 06:46:10 +00:00
|
|
|
end
|
|
|
|
end
|
2011-12-18 01:16:11 +00:00
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
def ssh_execute(vm, command=nil)
|
2011-12-26 17:58:10 +00:00
|
|
|
exit_status = 0
|
|
|
|
|
2011-12-18 01:16:11 +00:00
|
|
|
@logger.debug("Executing command: #{command}")
|
|
|
|
vm.ssh.execute do |ssh|
|
|
|
|
ssh.exec!(command) do |channel, type, data|
|
2011-12-26 17:58:10 +00:00
|
|
|
if type == :exit_status
|
|
|
|
exit_status = data.to_i
|
|
|
|
else
|
2011-12-18 01:16:11 +00:00
|
|
|
# Print the SSH output as it comes in, but don't prefix it and don't
|
|
|
|
# force a new line so that the output is properly preserved
|
|
|
|
vm.ui.info(data.to_s, :prefix => false, :new_line => false)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2011-12-26 17:58:10 +00:00
|
|
|
|
|
|
|
# Exit with the exit status we got from executing the command
|
|
|
|
exit exit_status
|
2011-12-18 01:16:11 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def ssh_connect(vm)
|
|
|
|
@logger.debug("`exec` into ssh prompt")
|
|
|
|
vm.ssh.connect
|
|
|
|
end
|
2010-08-25 06:46:10 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|