2

Is there a way to call a command like last inside a ruby script? I can use %x to call commands like ls and ls -l within a script, but would that be acceptable for the complex and constantly expanding log information provided by the last command?

sawa
  • 165,429
  • 45
  • 277
  • 381
yukimoda
  • 181
  • 10
  • See http://stackoverflow.com/questions/754494/reading-the-last-n-lines-of-a-file-in-ruby for a `last`-command in ruby. – knut Nov 27 '16 at 22:39

1 Answers1

2

Here's an example, to retrieve user name, ip, startup and duration :

%x(last -i).each_line do |line|
  line.chomp!                             # Removes newline
  break if line.empty?                    # last is done

  # 3 possibilities to extract information :
  user, *other_columns = line.split(' ')  # 1. Use split
  start = Time.parse(line[39,16])         # 2. Use known position of a column
  ip    = line[22,17].strip
  if line =~/\((\d+):(\d+)\)/             # 3. Use a regex
    duration = $1.to_i*60+$2.to_i
  else
    duration = nil
  end

  info={user: user, ip: ip, start: start, duration: duration}
  #TODO: Check that user isn't "reboot"
  puts info
end


# {:user=>"ricou", :ip=>"0.0.0.0", :start=>2016-11-01 21:29:00 +0100, :duration=>141}
# {:user=>"ricou", :ip=>"0.0.0.0", :start=>2016-11-01 15:21:00 +0100, :duration=>57}

Which information do you need exactly?

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124