Search code examples
linuxservicerpmsystemctl

Get running services and output the service with versions on linux


How would I get all the list of services that are running on linux and print their versions?

It needs to be a combination of:

To get a list of running Services:

systemctl list-units -t service --state=active --plain --no-legend --no-page

grab the name of each service and run:

rpm -q <service package name>

then get a table or json or csv kinda output:

nginx.service   1:1.20.1-2.el7

I am thinking of writing a python script to do this but I thought I would ask here in case there is a more linux/bash way of doing it with less effort.


Solution

  • #!/bin/bash
    
    listServices(){
       /bin/systemctl list-units -t service --state=active --plain --no-legend --no-page |
       awk -F[@\.] '{print $1}'
    }
    

    CSV

    while read -r service;do
       rpm -q "$service" --qf '%{NAME}.service;%{VERSION}\n'
    done < <(listServices)|grep -v "not installed"
    
    dbus.service;1.10.24
    firewalld.service;0.6.3
    ...
    

    Json:

    echo '['
    while read -r service;do
       rpm -q "$service" --qf '{"name": "%{NAME}.service", "version": "%{VERSION}"\},\n'
    done < <(listServices)|grep -v "not installed" |sed '$s/,$//'
    echo ']'
    
    
    [
        {
            "name": "dbus.service",
            "version": "1.10.24"
        },
        {
            "name": "firewalld.service",
            "version": "0.6.3"
        },
        {
        ...
    ]