与 psutil 一样,如何在 linux 中列出守护进程(服务)进程?

How to list daemon (services) process in linux, as with psutil?

我正在尝试使用 psutil

在 linux 中打印当前的 运行ning 服务(守护进程?)

在 windows 中,使用 psutil 我可以使用此代码获取当前 运行ning 服务:

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 中获得相同的效果,我尝试使用 subprocess 模块和 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....

谢谢

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


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

#!/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()