-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem_info.py
More file actions
233 lines (199 loc) · 6.6 KB
/
system_info.py
File metadata and controls
233 lines (199 loc) · 6.6 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import os
import platform
import datetime
import subprocess
import ctypes
def get_system_info():
"""
Collect system information including user, computer name, and login times.
"""
info = {
'username': _get_username(),
'computer_name': platform.node(),
'os_version': f"{platform.system()} {platform.release()} ({platform.version()})",
'exam_date_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'last_login': _get_last_login(),
'last_boot': _get_last_boot(),
'domain': _get_domain(),
'is_admin': _is_admin()
}
return info
def _get_username():
"""Get the currently logged in username."""
try:
return os.getlogin()
except:
try:
return os.environ.get('USERNAME', 'Unknown')
except:
return 'Unknown'
def _get_domain():
"""Get the computer domain or workgroup."""
try:
return os.environ.get('USERDOMAIN', 'Unknown')
except:
return 'Unknown'
def _is_admin():
"""Check if running with administrator privileges."""
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except:
return False
def _get_last_login():
"""
Get the last login timestamp from Windows Security Event Log.
Event ID 4624 = Successful logon
"""
ps_cmd = '''
try {
$event = Get-WinEvent -FilterHashtable @{
LogName='Security'
ID=4624
} -MaxEvents 1 -ErrorAction Stop
if ($event) {
$event.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss')
}
} catch {
# Try alternative method using net user
try {
$user = $env:USERNAME
$output = net user $user 2>$null
$lastLogon = ($output | Select-String "Last logon").ToString()
$lastLogon -replace "Last logon\s+", ""
} catch {
"Unable to retrieve"
}
}
'''
try:
result = subprocess.run(
["powershell", "-NoProfile", "-Command", ps_cmd],
capture_output=True, text=True, timeout=30
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except:
pass
# Fallback: Use WMI
try:
ps_wmi = '''
try {
$os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop
$os.LastBootUpTime.ToString('yyyy-MM-dd HH:mm:ss')
} catch {
"Unable to retrieve"
}
'''
result = subprocess.run(
["powershell", "-NoProfile", "-Command", ps_wmi],
capture_output=True, text=True, timeout=30
)
if result.returncode == 0 and result.stdout.strip():
return f"Since boot: {result.stdout.strip()}"
except:
pass
return "Unable to retrieve"
def _get_last_boot():
"""Get the last system boot time."""
ps_cmd = '''
try {
$os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop
$os.LastBootUpTime.ToString('yyyy-MM-dd HH:mm:ss')
} catch {
"Unable to retrieve"
}
'''
try:
result = subprocess.run(
["powershell", "-NoProfile", "-Command", ps_cmd],
capture_output=True, text=True, timeout=30
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except:
pass
return "Unable to retrieve"
def get_all_users():
"""Get list of all user accounts on the system."""
users = []
ps_cmd = '''
try {
Get-LocalUser | ForEach-Object {
"$($_.Name)|$($_.Enabled)|$($_.LastLogon)"
}
} catch {
# Fallback for older systems
net user 2>$null | Select-String -Pattern "^[A-Za-z]"
}
'''
try:
result = subprocess.run(
["powershell", "-NoProfile", "-Command", ps_cmd],
capture_output=True, text=True, timeout=30
)
if result.returncode == 0 and result.stdout.strip():
for line in result.stdout.strip().split('\n'):
if '|' in line:
parts = line.split('|')
if len(parts) >= 3:
users.append({
'name': parts[0],
'enabled': parts[1] == 'True',
'last_logon': parts[2] if parts[2] else 'Never'
})
except:
pass
return users
def get_recent_logons(max_events=50):
"""Get recent logon events from Security log."""
logons = []
ps_cmd = f'''
try {{
Get-WinEvent -FilterHashtable @{{
LogName='Security'
ID=4624
}} -MaxEvents {max_events} -ErrorAction Stop | ForEach-Object {{
$xml = [xml]$_.ToXml()
$user = ($xml.Event.EventData.Data | Where-Object {{$_.Name -eq 'TargetUserName'}}).'#text'
$domain = ($xml.Event.EventData.Data | Where-Object {{$_.Name -eq 'TargetDomainName'}}).'#text'
$logonType = ($xml.Event.EventData.Data | Where-Object {{$_.Name -eq 'LogonType'}}).'#text'
"$($_.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss'))|$domain\\$user|$logonType"
}}
}} catch {{
# Access denied or log not available
}}
'''
try:
result = subprocess.run(
["powershell", "-NoProfile", "-Command", ps_cmd],
capture_output=True, text=True, timeout=60
)
if result.returncode == 0 and result.stdout.strip():
for line in result.stdout.strip().split('\n'):
if '|' in line:
parts = line.split('|')
if len(parts) >= 3:
# Filter out system accounts
if not any(x in parts[1].lower() for x in ['system', 'dwm-', 'umfd-', '$']):
logons.append({
'time': parts[0],
'user': parts[1],
'logon_type': _logon_type_name(parts[2])
})
except:
pass
return logons
def _logon_type_name(logon_type):
"""Convert logon type number to human-readable name."""
types = {
'2': 'Interactive (local)',
'3': 'Network',
'4': 'Batch',
'5': 'Service',
'7': 'Unlock',
'8': 'NetworkCleartext',
'9': 'NewCredentials',
'10': 'RemoteInteractive (RDP)',
'11': 'CachedInteractive'
}
return types.get(logon_type, f'Type {logon_type}')