解析";ps aux";使用Ruby的Linux终端输出

解析";ps aux";使用Ruby的Linux终端输出,ruby,linux,Ruby,Linux,我试图制作一个程序,解析Linux命令ps aux的输出,其中的输出可以如下所示: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 2 0.0 0.0 0 0 ? S 20:04 0:00 [kthreadd] root 3 0.0 0.0 0 0 ? I< 20:0

我试图制作一个程序,解析Linux命令ps aux的输出,其中的输出可以如下所示:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         2  0.0  0.0      0     0 ?        S    20:04   0:00 [kthreadd]
root         3  0.0  0.0      0     0 ?        I<   20:04   0:00 [rcu_gp]
root         4  0.0  0.0      0     0 ?        I<   20:04   0:00 [rcu_par_gp]
root       397  0.0  0.1  95112 15236 ?        S<s  20:04   0:00 /lib/systemd/systemd-journald
root       431  0.0  0.0  46588  4640 ?        Ss   20:04   0:01 /lib/systemd/systemd-udevd
and so on...
def run_ps_aux()
    ps_aux = `ps aux`
    return run_ps_aux
end

puts run_ps_aux()
然而,我只对CPU、MEM和命令感兴趣。我希望得到如下输出:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         2  0.0  0.0      0     0 ?        S    20:04   0:00 [kthreadd]
root         3  0.0  0.0      0     0 ?        I<   20:04   0:00 [rcu_gp]
root         4  0.0  0.0      0     0 ?        I<   20:04   0:00 [rcu_par_gp]
root       397  0.0  0.1  95112 15236 ?        S<s  20:04   0:00 /lib/systemd/systemd-journald
root       431  0.0  0.0  46588  4640 ?        Ss   20:04   0:01 /lib/systemd/systemd-udevd
and so on...
def run_ps_aux()
    ps_aux = `ps aux`
    return run_ps_aux
end

puts run_ps_aux()
命令:CPU:MEM

命令:CPU:MEM

命令:CPU:MEM

等等

另外,是否可以进行排序,以便只获取CPU使用率最高的3个命令

感谢所有的帮助

%x{ ps aux }.lines # split string by newlines
            .drop(1) # skip the first line
            .map do |line| # iterate through the lines and return a new array
               columns= line.split(/\s+/, 11) # split line by one or more spaces
              "#{columns.last}:#{columns[2]}:#{columns[3]}"
            end
如果您想要更可重用的内容,可以返回哈希数组:

lines = %x{ ps aux }.lines
headers = lines.first.split(/\s+/)
               .map{|h| h.tr('%', '').downcase.intern }
lines.drop(1).map do |line|
  # creates a hash from an array of pairs
  Hash[headers.zip(line.split(/\s+/, 11))]
end

IMHO最简单的方法是运行此shell命令:

$ ps aux | tail -n +2 | awk '{print $11 ":" $3 ":" $4}'


您可以将此命令嵌入到Ruby程序中。

您还没有向我们展示解决您所问问题的方法。请参阅“”及其所有链接页面。如果没有证据显示您尝试了什么,看起来您没有尝试,并且希望我们为您编写代码,这是离题的。谢谢您的帮助,这太棒了。我会接受的。但是,如果命令包含空格,例如/usr/sbin/sshd-D-p2222不包含-D-p2222,则该命令将被剪切。再次感谢您的帮助。嗯,正则表达式模式可能需要一些改进来处理这种情况。@max在这种情况下,您可以将
line.split(/\s+/)
替换为
line.split(/\s+/,11)
$ ps aux | tail -n +2 | awk 'BEGIN {OFS=":"} {print $11, $3, $4}'