Created
October 5, 2016 07:38
-
-
Save larsoner/6b892c3c92bc9d5763739d96406d92ca to your computer and use it in GitHub Desktop.
Script to track user login/logout using UTMP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| import utmp | |
| import tabulate | |
| from warnings import warn | |
| def time_str(dt): | |
| """Convert datetime object to date-time string.""" | |
| return dt.strftime('%Y/%m/%d %H:%M:%S') | |
| state = None | |
| entries = [['user', 'login', 'logout', 'hours']] | |
| with open('wtmp', 'rb') as fd: | |
| buf = fd.read() | |
| for entry in utmp.read(buf): | |
| if entry.line == ':0': | |
| if state is None: | |
| if entry.user: | |
| state = 'out' | |
| else: | |
| continue | |
| if state == 'in': | |
| if entry.user: | |
| warn('double-login detected (user %s->%s)' | |
| % (entries[-1][0], entry.user,)) | |
| else: | |
| entries[-1] += [entry.time] | |
| state = 'out' | |
| else: | |
| assert state == 'out' | |
| if not entry.user: | |
| warn('logout detected without login') | |
| else: | |
| entries.append([entry.user, entry.time]) | |
| state = 'in' | |
| if len(entries[-1]) != 4: # didn't finish (will usually be the case) | |
| assert state == 'in' | |
| entries.pop(-1) | |
| # Do some nice formatting | |
| for entry in entries[1:]: | |
| entry.append('%0.3f' % ((entry[2] - entry[1]).total_seconds() / 3600.)) | |
| entry[1] = time_str(entry[1]) | |
| entry[2] = time_str(entry[2]) | |
| table = tabulate.tabulate(entries, 'firstrow') | |
| print(table) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment