我正在尝试编写一些可以连接到XenServer VM控制台(通过/usr/lib/xen/bin/xenconsole
)的ruby代码,首先通过SSH连接到主机服务器,然后从命令行访问VM控制台。
要做到这一点,我正在使用ruby库Net::SSH
。我正在通过SSH登录主机服务器并运行命令以获取VM的DOM ID。当我运行xenconsole命令时出现问题。您必须在命令后按“enter”才能转入控制台,然后必须按CTRL + ]
退出VM的控制台并返回主机的命令行。
我正在使用下面的代码,但它会在“按下输入”点处挂起,并且不会从SSH通道提供任何反馈,无论是STDOUT还是STDERR。如何访问VM的控制台以在VM上执行命令?那我该如何发送CTRL + ]
个字符?
def execute_remote_console(hostname, port, username, password, uuid)
begin
Net::SSH.start( hostname, username, :password => password, :port => port ) do |session|
dom_list_line = session.exec! "list_domains | grep #{uuid}"
if dom_list_line.match(/(\d+)/)
dom_id = $1
puts "found #{uuid} on DOM #{dom_id}"
else
raise "couldn't find DOM id"
end
console_command = "/usr/lib/xen/bin/xenconsole #{dom_id}"
puts "connecting to console: #{console_command}"
session.exec!( console_command ) do |ch,stream,data|
puts "pressing (enter)"
ch.send_data "\n"
case stream
when :stderr
puts "E-> #{data}"
ch.exec "cat /etc/hostname" do |chan, success|
raise "could not execute command" unless success
# "on_data" is called when the process writes something to stdout
chan.on_data do |c, data|
$STDOUT.print data
end
# "on_extended_data" is called when the process writes something to stderr
chan.on_extended_data do |c, type, data|
$STDERR.print data
end
chan.on_close { puts "done!" }
end
when :stdout
puts "O-> #{data}"
else
puts" other: #{data}"
end
end #end session.exec
end #end SSH.start
rescue
puts "\t\t\tok (#{$!.message})"
end
end #end function