keepwalk2020
2020-11-20 20:28:06 +08:00
在策略组设置好之后.每隔开一段时间给所有运行的 pid 做一次 snapshot,然后把 pid 映射成 exe 程序名称,如果发现目标程序不在了,就启动目标程序,如果发现目标程序还在,就什么都不做,具体代码实现如下:这个程序是守护 VNC,记得换成你需要守护的程序名称,运行环境 python 2.7
# -*- coding: utf-8 -*-
#!/usr/bin/python
import os, sys, gc, time, ctypes, subprocess
from ctypes import byref, sizeof, windll, c_size_t, c_char, c_void_p, Structure, WinError#, POINTER
from ctypes.wintypes import DWORD, LONG
class PROCESSENTRY32(Structure):
_fields_ = [
('dwSize', DWORD),
('cntUsage', DWORD),
('th32ProcessID', DWORD),
('th32DefaultHeapID', c_size_t),
('th32ModuleID', DWORD),
('cntThreads', DWORD),
('th32ParentProcessID', DWORD),
('pcPriClassBase', LONG),
('dwFlags', DWORD),
('szExeFile', c_char * 260),
] #LPPROCESSENTRY32 = POINTER(PROCESSENTRY32)
def syspid_snapshot(dwFlags=2, th32ProcessID=0):
hSnapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot(dwFlags,th32ProcessID)
INVALID_HANDLE_VALUE = ctypes.wintypes.c_void_p(-1).value
if hSnapshot == INVALID_HANDLE_VALUE: raise ctypes.WinError()
return hSnapshot
def get_all_explr_pids():
all_pid=[]
pse = PROCESSENTRY32()
pse.dwSize = ctypes.sizeof(PROCESSENTRY32)
hSnapshot = syspid_snapshot()
pse_crt = ctypes.windll.kernel32.Process32First(hSnapshot, ctypes.byref(pse))
while pse_crt:
try :
hProcess = ctypes.windll.kernel32.OpenProcess(0x0410, 0, pse.th32ProcessID)
if hProcess:
buf = (ctypes.c_wchar * 1024)()
ctypes.windll.psapi.GetModuleFileNameExW(hProcess, 0, ctypes.pointer(buf), 1024+1)
buf = buf[:].encode('utf-8')
buf = buf[:buf.index("\0")]
if str(buf).split('\\')[-1].lower() == 'vncserver.exe': all_pid.append( str(pse.th32ProcessID) )
except : return (-1,)
pse_crt = ctypes.windll.kernel32.Process32Next(hSnapshot, ctypes.byref(pse))
ctypes.windll.Kernel32.CloseHandle(hProcess)
ctypes.windll.Kernel32.CloseHandle(hSnapshot)
return tuple(all_pid)
def protect_VNC():
sys.stdout.write('Daemon started with pid %d\n' % os.getpid())
sys.stdout.write('Daemon stdout output\n')
sys.stderr.write('Daemon stderr output\n')
vnc_exe_path = r"C:\\Program Files\\RealVNC\\VNC Server\\vncserver.exe"
c = 0
while True:
sys.stdout.write('%d: %s\n' %(c, time.ctime()))
sys.stdout.flush()
c = c+1
time.sleep(60*20) #check vnc pid each 20 minutes
#time.sleep(12) #check vnc pid each 20 minutes
try:
vnc_flg = get_all_explr_pids()
print(vnc_flg)
except :
continue
if len(vnc_flg) > 0:
if vnc_flg[0] != -1:
print('vnc is running\n\n')
else :
print('can not find vnc pid \n\n')
try:
subprocess.Popen(vnc_exe_path)
except:
pass
else :
print('can not find vnc pid \n\n')
try :
subprocess.Popen(vnc_exe_path, shell=True)
#ppp = os.popen( vnc_exe_path ).read()
except :
pass
if __name__ == '__main__':
protect_VNC()