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?

1

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

The IP addresses. I figured I could use match to isolate them once I figured out how to get last working.
I updated the code. You might need to check that the columns have the same width as mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.