簡體   English   中英

與psutil一樣,如何在Linux中列出守護進程(服務)進程?

[英]How to list daemon (services) process in linux, as with 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中獲得相同的效果,我嘗試使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM