How to see a Windows service dependencies with Python?

送分小仙女□ 提交于 2019-12-11 16:13:42

问题


Using the Windows Services console, you can see a service dependencies under Properties > Dependencies. How you can you get the same information with Python? Is there a way to do it with psutil?


回答1:


You can use the subprocess module to query sc.exe to get info for your service and then parse out the dependencies information. Something like:

import subprocess

def get_service_dependencies(service):
    try:
        dependencies = []  # hold our dependency list
        info = subprocess.check_output(["sc", "qc", service], universal_newlines=True)
        dep_index = info.find("DEPENDENCIES")  # find the DEPENDENCIES entry
        if dep_index != -1:  # make sure we have a dependencies entry
            for line in info[dep_index+12:].split("\n"):  # loop over the remaining lines
                entry, value = line.rsplit(":", 2)  # split each line to entry : value
                if entry.strip():  # next entry encountered, no more dependencies
                    break  # nothing more to do...
                value = value.strip()  # remove the whitespace
                if value:  # if there is a value...
                    dependencies.append(value)  # add it to the dependencies list
        return dependencies or None  # return None if there are no dependencies
    except subprocess.CalledProcessError:  # sc couldn't query this service
        raise ValueError("No such service ({})".format(service))

Then you can easily query for dependencies as:

print(get_service_dependencies("wudfsvc"))  # query Windows Driver Foundation service
# ['PlugPlay', 'WudfPf']


来源:https://stackoverflow.com/questions/45254787/how-to-see-a-windows-service-dependencies-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!