Skip to content

Instantly share code, notes, and snippets.

@tatzyr
Created March 20, 2017 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatzyr/6f1eb6a32b07d0cf65416ca6cb8fd54e to your computer and use it in GitHub Desktop.
Save tatzyr/6f1eb6a32b07d0cf65416ca6cb8fd54e to your computer and use it in GitHub Desktop.
JSON output for top (1)
#!/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