wコマンドのParserをrubyで書いた。

/dev/pts以下にファイルがない時があったのでwコマンドをパースすることにした。(おそらくLXDコンテナ内だからかな)

  def idle_by_w_command
    cmd = "w | grep #{self.username} | awk '{print $5}'"
    output = self._exec(cmd, "admin")
    output.split("\n").map{|line|
      if line =~ /(\d+)days/
        $1.to_i * 3600 * 24
      elsif line =~ /(\d+):(\d+)m$/
        $1.to_i * 3600 + $2.to_i * 60
      elsif line =~ /(\d+):(\d+)$/
        $1.to_i * 60 + $2.to_i 
      elsif line =~ /([0-9]*[.])?[0-9]+s$/
        $1.to_i
      end
    }.compact
  end

Related Posts