Created
May 14, 2014 09:30
-
-
Save jay16/32666c43e1f24155027f to your computer and use it in GitHub Desktop.
This file contains 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" | |
#store options in hash | |
options = {} | |
opt_parse = OptionParser.new do |opts| | |
opts.banner = 'kp: kill multi process with keywords.' | |
opts.separator "" | |
opts.separator "Options" | |
# This displays the help screen, all programs are | |
# assumed to have this option. | |
opts.on('-h', '--help', 'display this usage page') do | |
puts opts; exit | |
end | |
opts.on('-k keywords', '--keywords keywords', Array, 'key words of process name, eg: [A,B].') do |value| | |
options[:keywords] = value | |
end | |
opts.separator "" | |
opts.separator "Commands" | |
opts.separator " kp -k resque" | |
opts.separator " kp -k resque,redis" | |
end | |
begin | |
opt_parse.parse! | |
rescue => e | |
puts opt_parse; exit | |
end | |
#show usage page when optins[:keywords] empty | |
if options[:keywords].nil? | |
puts opt_parse; exit | |
end | |
puts "kill process with keywords:" + options[:keywords].join(",") | |
keywords = options[:keywords].push("PID").join("|") | |
# execute shell command | |
# return [status, *ret] | |
def shell_cmd(cmd) | |
IO.popen(cmd) do |stdout| | |
stdout.reject(&:empty?) | |
end.unshift($?.exitstatus.zero?) | |
end | |
# shell command string | |
cmd = "ps aux | grep -E '#{keywords}' | grep -v 'grep' | grep -v '#{Process.pid}'" | |
status, *result = shell_cmd(cmd) | |
# execute error or result is empty | |
if !status or result.size == 1 | |
puts "shell command below:" | |
puts cmd | |
puts (!status ? "execute error:" : "result is empty:") | |
puts result.join("\n") | |
exit | |
end | |
# display result | |
result.each_with_index do |row, index| | |
puts (index.zero? ? "INDEX" : index).to_s.ljust(7, " ") + row | |
end | |
# transpose | |
title = result[0].split | |
result = result.map(&:split).map do |row| | |
row.first(title.size-1).push(row.last(row.size-title.size+1).join(" ")) | |
end | |
puts "type the index you kill (spareat by white space):\r" | |
input = STDIN.gets.strip.split | |
pid_index = title.index("PID") | |
cmd_index = title.index("COMMAND") | |
puts "kp result:" | |
result.each_with_index do |row, index| | |
tmp = row.values_at(pid_index, cmd_index) | |
printf("%-10s %-10s %-10s\n", *tmp.unshift("STATUS")) if index.zero? | |
#grep type index | |
if input.include?(index.to_s) | |
status, *ret = shell_cmd("kill -9 #{tmp[0]}") | |
printf("%-10s %-10s %-10s\n", *tmp.unshift(status ? "killed" : "FAIL")) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment