yukimoda yukimoda - 9 days ago 7
Bash Question

Calling a command inside a ruby script

So, this might be a dumb question but is there a way to call a command like 'last' inside a ruby script? I know that you 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? Like I said, this might be a dumb question but I'm new to ruby and I honestly haven't been able to find anything in regards to the last command.

Answer

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?