yukimoda
yukimoda

Reputation: 183

Calling a command inside a ruby script

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?

Upvotes: 2

Views: 41

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54213

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?

Upvotes: 2

Related Questions