gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:47 25 4
gpt4 key购买 nike

我正在尝试使用 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 中获得相同的效果,我尝试使用 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。


以下内容适用于使用 systemd 作为其初始系统的 Linux 发行版(这适用于大多数现代发行版——包括 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()

关于python - 如何在 linux 中列出守护进程(服务)进程,与 psutil 一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com