带有说明的tasklist命令 [英] tasklist command with description

查看:76
本文介绍了带有说明的tasklist命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出给出Description以及Taskmangaer UI中所示的Description命令?我试图从python运行它,如果不是可能的话,是否有等效的python命令来获取带有说明的所有任务的列表?

I am trying to figure out a tasklist command that gives the Description aswell as shown in the Taskmangaer UI?I am trying to run it from python,if it is not posible is there an equivalent python command to get list of all tasks with description?

tasklist /?

推荐答案

这比您想象的要棘手,您确实需要一个充分的理由来解决所有麻烦以证明其合理性.首先,任务管理器用户界面不会从tasklist.exe获取信息,尽管您可以通过以下方式获得非常接近的信息:

That's a bit trickier than you might imagine and you really need a good reason to go through all the trouble to justify it. First of all, Task Manager UI doesn't get its information from tasklist.exe, although you can get pretty close with:

import csv
import subprocess

try:
    tl_out = subprocess.check_output(["tasklist", "/fo", "csv", "/v"])
except subprocess.CalledProcessError as e:
    print("Call to `tasklist` failed: {}".format(e))
    exit(1)

tl_csv = csv.DictReader(tl_out.splitlines())
for row in tl_csv:
    print(row)  # prints a dict for each task with all available fields
    # Available fields (may vary from platform to platform) are:
    # 'Status', 'CPU Time', 'Image Name', 'Session Name', 'Window Title',
    # 'PID', 'User Name', 'Session#', 'Mem Usage'

但是,要进入Description字段(以及来自Task Manager UI的许多其他字段),您至少必须从WMI中提取数据.更糟的是,在

However, to get to the Description field (and a lot others from the Task Manager UI) you'll have to pull the data from WMI at the very least. To make matters worse, WMIC on Windows 7 has a bug when exporting to CSV making the whole thing even more complicated as for maximum portability we need to use the list format and parse it ourselves:

import subprocess

try:
    wmi_out = subprocess.check_output(["wmic", "process", "list", "full", "/format:list"])
except subprocess.CalledProcessError as e:
    print("Call to `wmic` failed: {}".format(e))
    exit(1)

# parse the WMI list:
wmi_entries = []
for task in wmi_out.strip().split("\r\r\n\r\r\n"):
    wmi_entries.append(dict(e.split("=", 1) for e in task.strip().split("\r\r\n")))

for row in wmi_entries:
    print(row)  # prints a dict for each task with all available fields
    # Available fields (may vary from platform to platform) are:
    # 'CSName', 'CommandLine', 'Description', 'ExecutablePath', 'ExecutionState', 'Handle',
    # 'HandleCount', 'InstallDate', 'KernelModeTime', 'MaximumWorkingSetSize',
    # 'MinimumWorkingSetSize', 'Name', 'OSName', 'OtherOperationCount', 'OtherTransferCount',
    # 'PageFaults', 'PageFileUsage', 'ParentProcessId', 'PeakPageFileUsage',
    # 'PeakVirtualSize', 'PeakWorkingSetSize', 'Priority', 'PrivatePageCount', 'ProcessId',
    # 'QuotaNonPagedPoolUsage', 'QuotaPagedPoolUsage', 'QuotaPeakNonPagedPoolUsage',
    # 'QuotaPeakPagedPoolUsage', 'ReadOperationCount', 'ReadTransferCount', 'SessionId',
    # 'Status', 'TerminationDate', 'ThreadCount', 'UserModeTime', 'VirtualSize',
    # 'WindowsVersion', 'WorkingSetSize', 'WriteOperationCount', 'WriteTransferCount'


Python3的代码更新(使用编码进行逐字节搜索):


Code Update for Python3 (use encode for bytes-wise search):

s1 = "\r\r\n\r\r\n".encode()
s2 = "\r\r\n".encode()
for task in wmi_out.strip().split(s1):
   wmi_entries.append(dict(e.split("=".encode(), 1) for e in task.strip().split(s2)))


如果不需要所有这些字段,则可以始终限制wmic来获取所需的字段(即wmi_out = subprocess.check_output(["wmic", "process", "get", "ProcessId,ExecutablePath,Description", "/format:list"])每个ProcessId仅获取Description).


If you don't need all these fields, you can always restrict wmic to get you the fields you want (i.e. wmi_out = subprocess.check_output(["wmic", "process", "get", "ProcessId,ExecutablePath,Description", "/format:list"]) to get only Description per ProcessId).

但是不要以为您的麻烦已经过去了-我们才刚刚开始.现在,我们有了Description字段(还有其他几个要引导的字段),您会注意到,对于那些没有宣布其描述的进程(其中大多数人,Windows程序员显然是懒惰的)或没有描述的服务-描述值仅包含可执行文件名称,即,如果您运行的是普通的旧记事本,则任务管理器用户界面将显示Notepad作为说明,而其词典条目将显示为notepad.exe-这是因为任务管理器UI使用了一种完全不同的方法任务列表,并直接从流程可执行文件获取描述.

But don't think your troubles are over - we just started. While we now have the Description field (and a few others to boot), you'll notice that for processes that do not announce their description (most of them, Windows programmers be lazy apparently) or services without a description - the description value just contains the executable name i.e. if you're running plain old Notepad, while Task Manager UI will show you Notepad as Description, its dictionary entry will have notepad.exe - that is because Task Manager UI uses a completely different approach to task list and gets the description directly from the process executable.

因此,实际上您需要一个额外的步骤来直接从其资源表中检索可执行文件的描述,这可能是调用Win32 API来获取描述的最简单的操作",因此您需要安装 pyWin32 模块首先:

So you actually need an additional step to retrieve the executable description directly from its resources table, which is probably the 'easiest' to do by invoking the Win32 API to get to the description, so you need to install the pyWin32 module first:

import subprocess
import win32api

# gets executable description via W32API
def get_executable_desc(path, default=''):
    try:
        language, codepage = win32api.GetFileVersionInfo(path, "\\VarFileInfo\\Translation")[0]
        return win32api.GetFileVersionInfo(path, "\\StringFileInfo\\{:04x}{:04x}\\FileDescription".format(language, codepage)) or default
    except:
        return default

try:
    wmi_out = subprocess.check_output(["wmic", "process", "list", "full", "/format:list"])
except subprocess.CalledProcessError as e:
    print("Call to `tasklist` failed: {}".format(e))
    exit(1)

# parse the WMI list:
wmi_entries = []
for task in wmi_out.strip().split("\r\r\n\r\r\n"):
    entry = dict(e.split("=", 1) for e in task.strip().split("\r\r\n"))
    entry['Description'] = get_executable_desc(entry.get("ExecutablePath", None), entry.get("Description", None))
    wmi_entries.append(entry)

for row in wmi_entries:
    print(row)  # prints a dict for each task with all available fields

Voilà!现在已经填充了描述(如果有的话,或者至少包含可执行文件的名称),但是由于我们必须使用Win32 API来获取描述,所以我们不妨获取任务通过它列出-更快,更简洁:

Voilà! Descriptions are now populated (where available, or at least hold the executable name), but since we had to use Win32 API to get to the descriptions, we might as well get the tasks list through it - it's faster and more concise:

from win32api import GetFileVersionInfo, OpenProcess
from win32con import PROCESS_QUERY_INFORMATION, PROCESS_VM_READ
from win32process import EnumProcesses, EnumProcessModules, GetModuleFileNameEx
import pywintypes

# gets executable description via W32API
def get_executable_desc(path, default=''):
    try:
        language, codepage = GetFileVersionInfo(path, "\\VarFileInfo\\Translation")[0]
        return GetFileVersionInfo(path, "\\StringFileInfo\\{:04x}{:04x}\\FileDescription".format(language, codepage)) or default
    except:
        return default

# gets the process list via W32API        
def get_process_list():
    proc_list = []
    processes = EnumProcesses()
    if not processes:
        return []  # optionally raise an exception, no ProcessIds could be obtained
    for proc in processes:
        try:
            handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, pywintypes.FALSE, proc)
            modules = EnumProcessModules(handle)
            if not modules:
                continue  # task died in the meantime?
            path = GetModuleFileNameEx(handle, modules[0])
            proc_list.append({"ProcessId": proc, "ExecutablePath": path, "Description": get_executable_desc(path, path)})
        except pywintypes.error as e:
            continue  # optionally report the error stored in `e`
    return proc_list

tasks = get_process_list()
for row in tasks:
    print(row)  # prints a dict for each task with ProcessId, ExecutablePath and Description fields

这将仅获取ProcessId,ExecutablePath和Description,但如果需要更多字段,则可以进一步探索Win32 API.

This will only get ProcessId, ExecutablePath and Description but you can further explore Win32 API if you need more fields.

同样,我看不到Description字段要经历所有这些麻烦有什么价值,但是如果您真的想要,那就是如何获得它.

Again, I don't see of what value the Description field is to go through all this trouble but if you really, really want it - this is how to get it.

这篇关于带有说明的tasklist命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆