Return to labs index

Assignment #2 - ttylast with AWK
Due: September 18, 2007

Overview

On a UNIX system, the last command provides you information about recent users. It includes when they were logged in, how long they stayed, where they came from, and their tty (terminal).

This assignment asks you to write ttylast that uses AWK to produce a version of the last output sorted by tty.

The Details

The format of the report should exactly match the format of the sample report. Since this script is to be standalone, it might be easier as a shell script that can pipe the results of "last" into awk, rather than a pure awk script. It is important to note that the output of ttylast does not contain multiple uses of a tty by a user -- only the most recent. This makes your life much easier.

In order to keep the assignment fun, you are allowed to use only the awk (awk, nawk or gawk) and last commands -- well, and, of course, a shell.

Some Hints

First, begin by looking at the output from my program. Then, take a look at the output of last. Make sure you understand the name of the game. To help you out, I included a copy of last's output captured from within my script, as well as my script's output.

There are many ways of solving this problem. As a hint, I'll tell you how I did it. As I worked my way through last's output one line at a time, I kept three arrays:

The first two arrays amount to nothing more than a list of users and a list of ttys, respectively. In reality, I really only cared about the keys, not the values.

The next array gave me the mapping. By building the "userid,tty" key", I gave myself an easy way to solve the problem. Essentially, I could find any pair. Invalid pairs would be the empty string "". So, if I'd look up "gkesden, pts/8" and gkesden didn't use pts/8, the result would be "".

So, to produce the output, I used two nested loops. The outer loop walked through the list of ttys. The inner loop walked through the lists of users. The code inside printed out the line of last mapped to "user,tty", well, at least unless that lookup yielded the empty string ("").

The last detail was the annoying extraneous line in last's output:

  wtmp begins Tue Sep 12 04:06:14 2006
  

To avoid this, I filtered by "action" so that it wouldn't happen if the pattern contained a "wtmp" in the first field.

One detail that I haven't given you: How to keep the most recent, rather than the least recent, use. Think about this one a bit. You'll likely want to reverse the output of last. This can be done with sed. Or, as an alternative, you can use nl to number the lines and then sort in reverse, and then whack the line numbers using, for example, awk or cut.

Sample Files

Since these files came from a real live unix system, you'll have to get them from AFS -- I don't want them to get crawled on the Web:

We're Here To Help!

As always -- remember, we're here to help!