最初 ssh username@hostname "コマンド" の形式で動いていたけど、途中でvirtualenvのworkonを実行すると「command not found」と言われたのでRubyで並列実行してみた。
Ruby便利ー
# ruby 2.1.5
require 'pty'
require 'expect'
def run console, host
timeout = 10
PTY.spawn "ssh #{host}" do |r, w, pid|
w.sync = true
r.expect console, timeout do
w.puts "date"
end
r.expect console, timeout do |capture|
# captureは[マッチした文字列, 正規表現のキャプチャ1, ...]
lines = capture[0].split "\n"
# linesの1行目は前回実行したコマンド、最終行はプロンプトなので削る
return lines.slice(1, lines.size - 2).join "\n"
end
end
end
def main console, hosts
$expect_verbose = false
threads = []
result = {}
hosts.each do |host|
threads << Thread.start do
result[host] = run console, host
end
end
threads.each do |thread|
thread.join
end
result.keys.sort.each do |host|
puts "#{host} : #{result[host]}"
end
end
if __FILE__ == $0
console = /\$$/
hosts = (1..10).map{|n| "username@example-#{n}.com"}
main console, hosts
end