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

2024-04-23 16:52:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

^{pr2}$

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

^{3}$

但这只能说明

python
init
bash

但当我运行service-status时,我得到了一个更大的列表,包括apache、sshd。。。。在

谢谢


Tags: 代码inselflogfor进程linuxwindows
1条回答
网友
1楼 · 发布于 2024-04-23 16:52:21

WSL中的service命令显示Windows服务。因为我们已经确定(在评论讨论中)您试图列出Linux服务,并且只将WSL用作测试平台,所以这个答案适用于大多数Linux发行版,而不是WSL。


以下将在Linux发行版上使用systemd作为其init系统(这适用于大多数现代发行版,包括当前的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()

相关问题 更多 >