Created
March 20, 2017 12:04
-
-
Save tatzyr/6f1eb6a32b07d0cf65416ca6cb8fd54e to your computer and use it in GitHub Desktop.
JSON output for top (1)
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 "json" | |
require "open3" | |
params = ARGV.getopts("cu:") | |
c_opt = params["c"] ? "-c" : "" | |
u_opt = params["u"] ? "-u #{params['u']}" : "" | |
o, e, s = Open3.capture3("COLUMNS=512 top -b -n 1 #{c_opt} #{u_opt}") | |
if s.exitstatus == 0 | |
keys = %w[PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND] | |
data = o.each_line.drop(7).map {|line| | |
values = line.match(/\A\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+?)\s*\Z/).captures | |
[keys, values].transpose.to_h | |
} | |
puts JSON.dump({ status: s.exitstatus, message: e.chomp, data: data }) | |
else | |
puts JSON.dump({ status: s.exitstatus, message: e.chomp, data: [] }) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment