-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprocess_monitor.py
73 lines (52 loc) · 1.97 KB
/
process_monitor.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
import win32con
import win32api
import win32security
import wmi
import sys
import os
LOG_FILE = "process_monitor_log.csv"
def get_process_privileges(pid):
try:
# obtain a handle to the target process
hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid)
# open the main process token
htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY)
# retrieve the list of privileges enabled
privs = win32security.GetTokenInformation(htok, win32security.TokenPrivileges)
# iterate over privileges and output the ones that are enabled
priv_list = []
for priv_id, priv_flags in privs:
# check if the privilege is enabled
if priv_flags == 3:
priv_list.append(win32security.LookupPrivilegeName(None, priv_id))
except:
priv_list.append("N/A")
return "|".join(priv_list)
def log_to_file(message):
fd = open(LOG_FILE, "ab")
fd.write("%s\r\n" % message)
fd.close()
return
# create a log file header
if not os.path.isfile(LOG_FILE):
log_to_file("Time,User,Executable,CommandLine,PID,ParentPID,Privileges")
# instantiate the WMI interface
c = wmi.WMI()
# create our process monitor
process_watcher = c.Win32_Process.watch_for("creation")
while True:
try:
new_process = process_watcher()
proc_owner = new_process.GetOwner()
proc_owner = "%s\\%s" % (proc_owner[0],proc_owner[2])
create_date = new_process.CreationDate
executable = new_process.ExecutablePath
cmdline = new_process.CommandLine
pid = new_process.ProcessId
parent_pid = new_process.ParentProcessId
privileges = get_process_privileges(pid)
process_log_message = "%s,%s,%s,%s,%s,%s,%s" % (create_date, proc_owner, executable, cmdline, pid, parent_pid,privileges)
print "%s\r\n" % process_log_message
log_to_file(process_log_message)
except:
pass