Skip to content

Instantly share code, notes, and snippets.

@arturopie
Created September 26, 2012 01:55
Show Gist options
  • Save arturopie/3785558 to your computer and use it in GitHub Desktop.
Save arturopie/3785558 to your computer and use it in GitHub Desktop.
Using EventMachine to execute commands in several host at once
require 'eventmachine'
require 'colorize'
class RemoteCommands < EM::Connection
attr_reader :queue
def initialize(q)
@queue = q
cb = Proc.new do |msg|
send_data("#{msg}\n")
q.pop &cb
end
q.pop &cb
end
def post_init
end
def receive_data data
puts "#{hostname.yellow} says:"
puts "#{@hostname} says #{data}"
end
def unbind
puts "Process died with exit status: #{get_status.exitstatus}"
EM.stop
end
private
def hostname
@hostname ||= `hostname`.gsub!(/\n/,"")
end
end
class KeyboardHandler < EM::Connection
include EM::Protocols::LineText2
attr_reader :queue
def initialize(q)
@queue = q
EM.add_timer(0.01) { print "> " }
end
def receive_line(data)
@queue.push(data)
EM.add_timer(0.01) { print "> " }
end
end
EM.run do
q = EM::Queue.new
EM.popen "ssh user1@host1", RemoteCommands, q
EM.popen "ssh user2@host2", RemoteCommands, q
EM.open_keyboard KeyboardHandler, q
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment