-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathids.py
73 lines (61 loc) · 1.96 KB
/
ids.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""Class for cache of UIDs"""
import json
import subprocess as sp
import sys
ID = "/bin/id"
class UserIDs(object):
"""Interface for handling the cache"""
def __init__(self, ids=None, name=None):
self.ids = ids if ids is not None else {}
def load(self, cache):
"""Attemtps to load preexisting cache"""
self.name = cache
try:
cache = open(cache)
self.ids = json.load(cache)
except:
pass
def access(self, user):
"""Access information in cache"""
return self.ids[user]
def add(self, user, uid):
"""Adds user and uid to cache"""
self.ids[user] = uid
self.ids[uid] = user
def have(self, user):
"""Check if user's information is in cache"""
return user in self.ids
def remove(self, user):
"""Remove user and uid from cache"""
try:
del self.ids[self.ids[user]]
del self.ids[user]
return 0
except KeyError:
return 1
def clear(self):
"""Clear cache"""
self.ids.clear()
def resolve(self, user, pslines, unknowns):
"""Resolves finding unknown UIDs"""
try:
return sp.check_output([ID, "-u", user], stderr=sys.stderr).rstrip()
except sp.CalledProcessError:
try:
for line in pslines:
if line.strip().split()[0] == user:
search = line[65:]
found = search.find("sshd: ")
if found != -1:
return search[6:13]
unknowns.add(user)
return None
except sp.CalledProcessError:
unknowns.add(user)
return None
def close(self):
"""Safely closes and saves cache"""
id_json = json.dumps(self.ids)
json_file = open(self.name, "w")
json_file.write(id_json)
json_file.close()