Home > Mobile >  Get running services and output the service with versions on linux
Get running services and output the service with versions on linux

Time:07-18

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.

CodePudding user response:

I have solved it using a bash script, I am posting here but also if there is a better way and/or a way to improve this, please let me know.

Create the file:

vim /tmp/service.sh

File content:

#!/bin/sh
/bin/systemctl list-units -t service --state=active --plain --no-legend --no-page > /tmp/service.list

services=( $(awk '/(.*)\.service/{print $1}' /tmp/service.list) )

for service in "${services[@]}"
do
        service=${service%.*}
        rpm -q ${service}
done

Then run the script:

/tmp/service.sh | grep -v "installed"

Running the script with "grep -v" means exclude all the entries from output which says package is not installed, leaving me with exactly what I need.

CodePudding user response:

#!/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"
    },
    {
    ...
]
  • Related