Help us understand the problem. What is going on with this article?

複数のサーバでインタラクティブにコマンドを実行する

More than 3 years have passed since last update.

最初 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
tadokoro
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away