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?
Asked
Active
Viewed 39 times
2
-
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 Answers
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
-
The IP addresses. I figured I could use match to isolate them once I figured out how to get last working. – yukimoda Nov 27 '16 at 22:32
-
I updated the code. You might need to check that the columns have the same width as mine. – Eric Duminil Nov 27 '16 at 22:44