-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutmp_reader.py
46 lines (34 loc) · 1.05 KB
/
utmp_reader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import collections
import datetime
import struct
from enum import Enum
class UTmpRecordType(Enum):
empty = 0
run_lvl = 1
boot_time = 2
new_time = 3
old_time = 4
init_process = 5
login_process = 6
user_process = 7
dead_process = 8
accounting = 9
def convert_string(val):
if isinstance(val, bytes):
return val.rstrip(b'\0').decode()
return val
class UTmpRecord(collections.namedtuple('UTmpRecord',
'type pid line id user host exit0 exit1 session' +
' sec usec addr0 addr1 addr2 addr3 unused')):
@property
def type(self):
return UTmpRecordType(self[0])
@property
def time(self):
return datetime.datetime.fromtimestamp(self.sec) + datetime.timedelta(microseconds=self.usec)
STRUCT = struct.Struct('hi32s4s32s256shhiii4i20s')
def read(buf):
offset = 0
while offset < len(buf):
yield UTmpRecord._make(map(convert_string, STRUCT.unpack_from(buf, offset)))
offset += STRUCT.size