首页 > 解决方案 > 如何在 linux 中列出守护进程(服务)进程,就像 psutil 一样?

问题描述

我正在尝试使用 psutil 在 linux 中打印当前正在运行的服务(守护进程?)

在 Windows 中,使用 psutil 我可以使用以下代码获取当前正在运行的服务:

def log(self):
        win_sev = set()
        for sev in psutil.win_service_iter():
            if sev.status() == psutil.STATUS_RUNNING:
                win_sev.add(sev.display_name())
        return win_sev

我想在linux中得到同样的效果,我尝试使用子进程模块和POPEN


 command = ["service", "--status-all"]  # the shell command
 p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)        
 result = p.communicate()[0]
 print result

但是我想知道我是否可以使用 psutil 获得相同的结果,我尝试使用

psutil.pids()

但这仅表明

python
init
bash

但是当我运行 service --status-all 时,我会得到一个更大的列表,包括 apache、sshd ....

谢谢

标签: pythonlinuxpsutil

解决方案


serviceWSL 中的命令显示Windows服务。正如我们已经确定(在评论中的讨论中)您正在尝试列出Linux服务,并且仅将 WSL 用作测试平台,因此编写此答案是为了适用于大多数 Linux 发行版,而不是适用于 WSL。


以下将适用于使用 systemd 作为其 init 系统的 Linux 发行版(这适用于大多数现代发行版——包括 Arch、NixOS、Fedora、RHEL、CentOS、Debian、Ubuntu 等的当前版本)。它在 WSL 上不起作用——至少不是你引用的版本,它似乎没有使用 systemd 作为它的 init 系统。

#!/usr/bin/env python

import re
import psutil

def log_running_services():
    known_cgroups = set()
    for pid in psutil.pids():
        try:
            cgroups = open('/proc/%d/cgroup' % pid, 'r').read()
        except IOError:
            continue # may have exited since we read the listing, or may not have permissions
        systemd_name_match = re.search('^1:name=systemd:(/.+)$', cgroups, re.MULTILINE)
        if systemd_name_match is None:
            continue # not in a systemd-maintained cgroup
        systemd_name = systemd_name_match.group(1)
        if systemd_name in known_cgroups:
            continue # we already printed this one
        if not systemd_name.endswith('.service'):
            continue # this isn't actually a service
        known_cgroups.add(systemd_name)
        print(systemd_name)

if __name__ == '__main__':
    log_running_services()

推荐阅读