修复循环以保存必要的Windows进程及其路径,并终止其余进程

时间:2016-10-31 12:36:37

标签: windows batch-file cmd wmic

我想保存一些系统进程及其路径,以确保系统不会崩溃,并终止进程的其余部分

示例:lsass.exe,winlogon.exe,conhost.exe,rundll32.exe等

这是我的.bat:

set proc=,
:: proc
call:proc "lsass.exe"
call:proc "winlogon.exe"
call:proc "conhost.exe"
call:proc "rundll32.exe"

for /f "skip=3 tokens=1 delims= " %%a in ('tasklist /fi "username eq %username%"') do (
echo %proc%, | findstr /c:,%%a, 1>nul
if errorlevel 1 (
taskkill /f /im %%a /t
) else (
echo not kill
)
)

:: funcion proc
@echo off
pause
goto:eof
:proc
set getproc=%1
for /f "tokens=1 delims=," %%F in ('tasklist /nh /fi "imagename eq %getproc%" /fo csv') do set proc=%proc%,%%~F>nul
goto:eof

问题是我的脚本没有保存进程的路径,那么,如果在另一个位置运行了一个假进程,我的脚本会保存这两个进程。这就是为什么我需要保存Windows系统进程,包括其原始路径

示例实际过程:

wmic process where "name='lsass.exe'" get ExecutablePath

真实的过程:

C:\Windows\system32\lsass.exe

虚假过程示例:

Out XP:

 C:\Documents and Settings\User\Local settings\Application Data\lsass.exe

或Out 7

 C:\Users\User\AppData\Roaming\lsass.exe
 c:\Users\User\Local Setting\Temp\lsass.exe
 c:\Users\User\AppData\Local\lsass.exe

注意:虚假进程可以从任何路径运行(与false进程关联的.exe文件可以存储在PC上的任何位置),系统文件夹除外(%windir%/ system32%windir%/ sysWOW64%windir%等)

不幸的是,到目前为止,我的脚本并未关闭虚假进程,只有我可以使用Process Explorer手动关闭

请求:我需要的是使用原始路径保存实际进程(lsass.exe,winlogon.exe等),并杀死其余的。感谢

2 个答案:

答案 0 :(得分:2)

this solution

检查@JosefZ
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

REM note double quotes                          REM added for debugging ↓↓↓↓↓↓↓↓↓↓↓↓
set "_var="%userprofile%","%Appdata%","%HOMEPATH%","%homedrive%\ProgramData","D:\Remote""
                                                REM added for debugging ↑↑↑↑↑↑↑↑↑↑↑↑

REM wmic requires double backslashes in specified path 
set "_var=%_var:\=\\%"

for %%G in  (%_var%) do (
rem echo processing %%G
  REM used `GET Caption` for debugging
rem WMIC PROCESS WHERE "Name = '%~1' and ExecutablePath Like '%%%%~G%%'" GET Caption

  REM operational 
WMIC PROCESS WHERE "Name = '%~1' and ExecutablePath Like '%%%%~G%%'" Call terminate 
)

答案 1 :(得分:0)

直接尝试使用WMIC。

@echo off
call :proc "lsass.exe"
call :proc "winlogon.exe"
call :proc "conhost.exe"
call :proc "rundll32.exe"
call :proc "services.exe
exit/b

:proc
WMIC PROCESS WHERE "Name='%~1' AND ExecutablePath Like '%%\\AppData\\%%'" CALL Terminate

[编辑/] 由于无法确定可能适合您的目的的每个进程,因此在cmd提示窗口中输入的以下内容应该关闭不在包含 \ Windows \ \ Program Files 。使用它是你自己的危险。

WMIC PROCESS WHERE "NOT ExecutablePath LIKE '%\\Windows\\%' AND NOT ExecutablePath LIKE '%\\Program Files%'" CALL TERMINATE