Created
May 22, 2012 14:04
-
-
Save mirakui/2769295 to your computer and use it in GitHub Desktop.
Remote operation script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ cat script.txt | |
grep hoge /var/log/nginx/access.log | |
$ rop.rb -H 'app-0{01..05}' -f script.txt | |
/tmp/rop/0522-2306-11/app-001 | |
/tmp/rop/0522-2306-11/app-002 | |
/tmp/rop/0522-2306-11/app-003 | |
/tmp/rop/0522-2306-11/app-004 | |
/tmp/rop/0522-2306-11/app-005 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'optparse' | |
require 'fileutils' | |
def sh(*cmd) | |
puts cmd.join(" ") if $verbose | |
system *cmd | |
end | |
def expand_brace(str) | |
`zsh -c 'echo #{str}'`.split | |
end | |
def ssh(host, command, *options) | |
sh "ssh", host, command | |
end | |
def scp(src, dst, *options) | |
options << "-q" unless $verbose | |
sh "scp", *[options, src, dst].flatten | |
end | |
def whoami | |
$whoami ||= `whoami`.chomp | |
end | |
def result_dir | |
$result_dir ||= begin | |
dir = "/tmp/rop/#{Time.now.strftime("%m%d-%H%M-%S")}" | |
FileUtils.mkdir_p dir unless File.exists? dir | |
end | |
end | |
def scp_exec(host, script_path, *scp_options) | |
script_name = script_path.split("/").last | |
result_path = "#{result_dir}/#{host}" | |
remote_script_path = "/tmp/rop.#{whoami}.#{script_name}" | |
remote_result_path = "#{remote_script_path}.result" | |
scp script_path, "#{host}:#{remote_script_path}" | |
ssh host, "bash #{remote_script_path} > #{remote_result_path} 2>&1" | |
scp "#{host}:#{remote_result_path}", result_path | |
ssh host, "rm /tmp/rop.#{whoami}.*" | |
result_path | |
end | |
module Enumerable | |
def parallel_each(n_threads=3) | |
queue = to_a.dup | |
threads = [] | |
n_threads.times do |i| | |
threads << Thread.new do | |
while elm = queue.shift | |
puts "thread(#{i}): #{elm}" if $verbose | |
yield elm | |
end | |
end | |
end | |
threads.each {|th| th.join } | |
end | |
end | |
$n_threads = 5 | |
opt = OptionParser.new | |
opt.on("-v") { $verbose = true } | |
opt.on("-H hosts") {|v| $hosts = expand_brace(v) } | |
opt.on("-f script") {|v| $script = v } | |
opt.on("-n threads") {|v| $n_threads = v.to_i } | |
opt.parse! | |
if File.exists? $script | |
$hosts.parallel_each($n_threads) do |h| | |
result_path = scp_exec h, $script | |
puts result_path | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment