1
+ #-*- coding:utf8 -*-
2
+
3
+ """
4
+ @version:
5
+ @author: giantbranch
6
+ @file: process_monitor.py
7
+ @time: 2016/3/13 20:12
8
+ """
9
+
10
+ import win32con
11
+ import win32api
12
+ import win32security
13
+
14
+ import wmi
15
+ import sys
16
+ import os
17
+
18
+ def get_process_privileges (pid ):
19
+ try :
20
+ # 通过pid获取目标进程句柄
21
+ hproc = win32api .OpenProcess (win32con .PROCESS_QUERY_INFORMATION , False , pid )
22
+
23
+ # 打开主进程的令牌
24
+ htok = win32security .OpenProcessToken (hproc , win32con .TOKEN_QUERY )
25
+
26
+ # 解析已启用的权限列表,获得令牌信息
27
+ privs = win32security .GetTokenInformation (htok , win32security .TokenPrivileges )
28
+
29
+ # 迭代每个权限并输出其中已经启用的
30
+ # i[0]:具体权限
31
+ # i[1]:该权限是否启用
32
+ priv_list = ""
33
+ for i in privs :
34
+ # 检测权限是否已经启用
35
+ if i [1 ] == 3 :
36
+ # 获取并连接权限的名称
37
+ priv_list += "%s|" % win32security .LookupPrivilegeName (None , i [0 ])
38
+ except :
39
+ priv_list = "N/A"
40
+
41
+ return priv_list
42
+
43
+
44
+ # 保存数据到文件中
45
+ def log_to_file (message ):
46
+ fd = open ("process_monitor_log.csv" , "ab" )
47
+ fd .write ("%s\r \n " % message )
48
+ fd .close ()
49
+
50
+ return
51
+
52
+ # 创建一个日志文件的头
53
+ log_to_file ("Time,User,Executable,CommandLine,PID,Parent PID,Privileges" )
54
+
55
+ # 初始化WMI接口
56
+ c = wmi .WMI ()
57
+
58
+ # 创建进程监控器(监控进程创建)
59
+ process_watcher = c .Win32_Process .watch_for ("creation" )
60
+
61
+ while True :
62
+ try :
63
+ # 有创建进程事件会返回
64
+ new_process = process_watcher ()
65
+
66
+ proc_owner = new_process .GetOwner ()
67
+ # for i in proc_owner:
68
+ # print i
69
+ proc_owner = "%s\\ %s" % (proc_owner [0 ], proc_owner [2 ])
70
+ # 时间
71
+ create_data = new_process .CreationDate
72
+ # 路径
73
+ executable = new_process .ExecutablePath
74
+ # 命令行(就是实际的命令是什么)
75
+ cmdline = new_process .CommandLine
76
+ pid = new_process .ProcessId
77
+ parent_pid = new_process .ParentProcessId
78
+
79
+ # N/A:不可用的意思
80
+ # privileges = "N/A"
81
+ privileges = get_process_privileges (pid )
82
+
83
+ process_log_message = "%s,%s,%s,%s,%s,%s,%s\r \n " % (create_data , proc_owner , executable , cmdline , pid , parent_pid , privileges )
84
+
85
+ print process_log_message
86
+
87
+ log_to_file (process_log_message )
88
+
89
+ except :
90
+ pass
0 commit comments