Linux systemctl services list

10+ commands to list all systemctl services with status

Table of Contents

In this tutorial I will share the commands which you can use to list systemctl services along with their state. You can use these methods in scripts to add service status checks to make sure service is in running or failed state.

Are you new to systemd and systemctl?

With RHEL/CentOS 7, now we have services based on systemd and the SysV scripts are deprecated. If you are new to systemd then I would suggest reading this another article where I have done 1:1 comparison between SysV and systemd services.

Now with systemd the traditional Linux commands such as chckconfig , service etc are not supported any more. Although you can still use these commands but they can be removed in upcoming releases.

For example, with RHEL/CentOS 6 we used to use chkconfig to enable or disable service at different run level. Now with RHEL 8 also I see we are allowed to use chkconfig

But the request is internally routed to systemctl . Similarly you can restart a service using traditional command i.e. service . For example, to restart sshd :

This request was also transferred to systemctl .

So I hope you understood the point, at the time of writing this article with RHEL 8.1

we are still allowed to use traditional SysV commands but it can be removed in any release now. So I would strongly recommend users to start using systemctl commands as they are very user friendly and powerful tool with the amount of options they support.

systemctl list unit files loaded in memory

List active unit files

First of all we will list all the unit files which are currently available in the memory of our Linux server. This command will list only the active units from the server’s memory:

systemctl list-units

List all the unit files

To list all the units independent of their state add » —all » to this command

systemctl list-units —all

As you can see now it is loading all the unit files including failed , inactive unit files

systemctl list installed unit files

Now list-units shows the list of units which are currently loaded in the memory but not necessarily installed on the server. To view the list of unit files which are currently installed on our server we use:

systemctl list-unit-files

List type of unit files

There can be different types of unit files such as service, socket, mount etc. To further filter the unit files we can add type= argument with list-unit-files . The argument should be a comma-separated list of unit types.

systemctl list services

To list all the installed systemctl services from our Linux server:

systemctl list services

This should give us a complete list of installed services (independent of it’s state)

systemctl list mount files

With systemd all the partitions and file system are mounted as part of mount type unit files. So we can also list all the mount type unit files available on our server using type=mount

systemctl list mount

We can further use this with different other type of unit files such as socket, target etc.

List state of services

systemctl list enabled services

To list all the service unit files which are currently in enabled state use —state=enabled

systemctl list enabled services

systemctl list disabled services

We can provided multiple state type with —state= argument where individual state values will be comma separated. For example to list all the systemctl service which are either enabled or disabled

systemctl list enabled and disabled services

systemctl list running services

To list the running services we will use list-units in combination with —type=service and —state=running

systemctl list running services

systemctl list failed services

To list failed services you can use —state=failed

OR alternatively we can directly use

systemctl list failed services

Check service status of individual unit file

Now the above commands will give you the status of all the unit files which are installed or available on your server. To check the status of individual file we do not want to use those commands in combination with grep and other filter utility.

Читайте также:  Файловая система windows информатика

Now assuming I wish to check the status of sshd service. So I can use

which can give me a long list of output along with the actual status such as active, running loaded. Now these three states can also be grepped individually using the properties of a unit file

To check if a systemctl service is running or not use:

To check if a service is active or inactive :

OR you can also use:

To check if a service is loaded or not:

So we can individually grep the state of individual services using their properties. To list all the properties of a service you can use:

Conclusion

In this article we learned little bit more about systemd and systemctl unit files. I have explained about the different types of unit files and commands using which we can get the list of running services, sockets, targets etc with systemctl . We can also get individual status of services using the property of unit files which gives us much more control over the details of each service. We can use these properties in scripts for automation purpose.

Lastly I hope the steps from the article to list running services on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

References

I have used below external references for this tutorial guide

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

1 thought on “10+ commands to list all systemctl services with status”

Amazing post, much gratitude for this great information!

Источник

How to List All Running Services Under Systemd in Linux

A Linux systems provide a variety of system services (such as process management, login, syslog, cron, etc.) and network services (such as remote login, e-mail, printers, web hosting, data storage, file transfer, domain name resolution (using DNS), dynamic IP address assignment (using DHCP), and much more).

Technically, a service is a process or group of processes (commonly known as daemons) running continuously in the background, waiting for requests to come in (especially from clients).

Linux supports different ways to manage (start, stop, restart, enable auto-start at system boot, etc.) services, typically through a process or service manager. Most if not all modern Linux distributions now use the same process manager: systemd.

Systemd is a system and service manager for Linux; a drop-in replacement for the init process, which is compatible with SysV and LSB init scripts and the systemctl command is the primary tool to manage systemd.

In this guide, we will demonstrate how to list all running services under systemd in Linux.

Listing Running Services Under SystemD in Linux

When you run the systemctl command without any arguments, it will display a list of all loaded systemd units (read the systemd documentation for more information about systemd units) including services, showing their status (whether active or not).

To list all loaded services on your system (whether active; running, exited or failed, use the list-units subcommand and —type switch with a value of service.

List All Services Under Systemd

And to list all loaded but active services, both running and those that have exited, you can add the —state option with a value of active, as follows.

List All Active Running Services in Systemd

But to get a quick glance of all running services (i.e all loaded and actively running services), run the following command.

List Running Services in Systemd

If you frequently use the previous command, you can create an alias command in your

/.bashrc file as shown, to easily invoke it.

Then add the following line under the list of aliases as shown in the screenshot.

Create a Alias for Long Command

Save the changes in the file and close it. And from now onwards, use the “running_services” command to view a list of all loaded, actively running services on your server.

View All Running Services

Besides, an important aspect of services is the port they use. To determine the port a daemon process is listening on, you can use the netstat or ss tools as shown.

Where the flag -l means print all listening sockets, -t displays all TCP connections, -u shows all UDP connections, -n means print numeric port numbers (instead of application names) and -p means show application name.

The fifth column shows the socket: Local Address:Port. In this case, the process zabbix_agentd is listening on port 10050.

Читайте также:  Центр обновления windows код ошибки 0x80070002

Determine Process Port

Also, if your server has a firewall service running, which controls how to block or allow traffic to or from selected services or ports, you can list services or ports that have been opened in the firewall, using the firewall-cmd or ufw command (depending on the Linux distributions you are using) as shown.

List Open Services and Ports on Firewall

That’s all for now! In this guide, we demonstrated how to view running services under systemd in Linux. We also covered how to check the port a service is listening on and how to view services or ports opened in the system firewall. Do you have any additions to make or questions? If yes, reach us using the comment form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Управление службами Linux

В операционной системе linux, так же как и в Windows, кроме обычных программ, которые могут взаимодействовать с пользователем есть еще один вид программ. Это работающие в фоне службы. Важность служб тяжело переоценить, они следят за состоянием системы, обеспечивают автоматическое подключение внешних устройств и сети, позволяют процессам взаимодействовать с оборудованием (dbus), а также в виде служб реализованы различные веб-серверы и серверы баз данных. В отличие от пользовательских программ, службы выполняются в фоне, и пользователь не имеет к ним прямого доступа. Пользователь еще не вошел в систему, только началась загрузка а основные службы уже запущенны и работают.

В этой статье мы рассмотрим управление службами Linux. Мы не будем трогать уже устаревшие системы, такие как SysVinit, сосредоточимся только на Systemd. Вы узнаете, как посмотреть запущенные службы linux, а также останавливать и запускать их самому.

Немного теории

Чтобы всем этим управлять нужна основная служба — система инициализации, которая будет запускать службы linux в нужный момент, следить чтобы они нормально работали, записывать сообщения логов, и самое главное позволять останавливать службы. Раньше, для управления службами использовались скрипты. Я уже говорил, что можно запустить службу из терминала, так вот, каждая служба запускалась в фоновом режиме одна за другой, без возможности параллельного запуска и возвращала свой PID процесса скрипту инициализации, он сохранялся и потом с помощью этого PID можно было проверить работает ли служба и остановить службу linux если это нужно. Все это можно сделать и вручную.

Но потом на смену этому методу пришла новая модель и система инициализации systemd. Система инициализации запускается сразу после загрузки ядра и начинает инициализировать службы, теперь появилась возможность параллельной инициализации, а также зависимостей между службами. Таким образом, теперь можно определить сложное дерево порядка запуска служб. Но мы не будем вникать в подробности создания служб, нас интересует только сам процесс запуска. После запуска systemd собирает весь вывод службы в лог, и следит за ее работой, если служба аварийно завершилась, то автоматически ее перезапускает.

Служба в Systemd описывается файлом юнита, в нем описано что с ней нужно делать и как себя вести. Существуют такие типы служб:

  • service — обычная служба, программа
  • target — группа служб
  • automount — точка автоматического монтирования
  • device — файл устройства, генерируется на этапе загрузки
  • mount — точка монтирования
  • path — файл или папка
  • scope — процесс
  • slice — группа системных служб systemd
  • snapshot — сохраненное состояние запущенных служб
  • socket — сокет для взаимодействия между процессами.

Нас будут интересовать только service, и совсем немного target, но мы рассмотрели все остальные, чтобы вы смогли взглянуть на картину немного шире. Основы рассмотрели, теперь будет настройка служб LInux.

Утилита systemctl

В Systemd есть специальный инструмент для управления службами в Linux — systemctl. Эта утилита позволяет делать очень много вещей, начиная от перезапуска службы linux и проверки ее состояния, до анализа эффективности загрузки службы. Синтаксис у утилиты такой:

$ systemctl опции команда служба служба.

Опции настраивают поведение программы, подробность вывода, команда — указывает что нужно сделать со службой, а служба, это та самая служба, которой мы собираемся управлять. В некоторых случаях утилита может использоваться без указания команды и службы.

Рассмотрим все по порядку. Опции очень сильно зависят от команд, поэтому рассмотрим их позже, а пока пройдемся по командах:

  • list-units — посмотреть все службы (юниты), аналог опции -t
  • list-sockets — посмотреть все службы сокетов
  • start — запустить службу linux
  • stop — остановить службу linux
  • reload — обновить конфигурацию службы из файла юнита
  • restart — перезапустить службу
  • try-restart — перезапустить службу, только если она запущена
  • reload-or-restart — обновить конфигурацию затем выполнить перезапуск службы linux, если не поддерживается — только перезапустить
  • isolate — запустить только одну службу вместе с ее зависимостями, все остальные остановить
  • kill — отправить сигнал завершения процессу используется вместе с опциями —signal и —kill-who
  • is-active — проверить запущена ли служба linux
  • is-failed — проверить не завершилась ли служба с ошибкой
  • status — посмотреть состояние и вывод службы
  • show — посмотреть параметры управления службой в Linux
  • reset-failed — перезапустить службы linux, завершившиеся с ошибкой
  • list-dependencies — посмотреть зависимости службы linux
  • list-unit-files — вывести все установленные файлы служб
  • enable — добавить службу в автозагрузку
  • disable — удалить службу из автозагрузки
  • is-enabled — проверить если ли уже служба в автозагрузке
  • reenable — сначала выполнить disable потом enable для службы
  • list-jobs — все запущенные службы linux независимо от типа
  • snapsot — сохранить состояние служб, чтобы потом восстановить
  • daemon-reload — обновить конфигурацию всех служб
  • mask — сделать юнит недоступным
  • unmask — вернуть файл службы linux
Читайте также:  Windows 10 pro 20h2 обновить

А теперь основные опции:

  • -t, —type — тип служб для вывода
  • -a, —all — показать все известные службы, даже не запущенные
  • -q — минимальный вывод
  • —version — версия программы
  • —no-pager — не использовать постраничную навигацию
  • —no-legend — не выводить подробное описание
  • -f — принудительное выполнение команды
  • —runtime — не сохранять вносимые изменения после перезагрузки
  • -n — количество строк вывода лога для команды status
  • —plain — использовать обычный текстовый режим вместо деревьев
  • —kill-who — задать процесс, которому нужно отправить сигнал
  • —signal — сигнал, который нужно отправить.
  • —state — отфильтровать список служб по состоянию.

Как видите, опции будут мало полезны и лучше обратить больше внимания на команды, с помощью них выполняются все действия.

Управление службами Linux

Теперь, когда вы уже знаете все основы, команды и параметры можно переходить к делу. Со всеми остальными тонкостями разберемся по пути. Сначала давайте посмотрим запущенные службы linux. Нас будут интересовать только программы, а не все эти дополнительные компоненты, поэтому воспользуемся опцией type:

systemctl list-units —type service

Команда отобразила все службы, которые известны systemd, они сейчас запущены или были запущены. Программа не пересматривает все файлы, поэтому будут показаны только те службы, к которым уже обращались. Состояние loaded — означает, что конфигурационный файл был успешно загружен, следующая колонка active — служба была запущена, а running или exited значит выполняется ли сейчас служба или она успешно завершила свою работу. Листать список можно кнопками вверх/вниз.

Следующая команда позволяет получить список служб linux, в который входят все службы, даже не запущенные, те, которые не запускались, но известны systemd, но это еще не все службы в системе:

systemctl list-units —type service -all

Дальше больше. Вы можете отсортировать список служб systemctl по состоянию. Например, только выполняющиеся:

systemctl list-units —type service —state running

Или те, которые завершились с ошибкой:

systemctl list-units —type service —state failed

Для фильтрации можно брать любой показатель состояния из любой колонки. Другой командой мы можем посмотреть все файлы конфигурации служб на диске. Тут не будем фильтровать по типу, пусть программа покажет все:

Теперь отфильтруем только службы linux:

systemctl list-unit-files —type service

Здесь вы тоже можете использовать фильтры по состоянию. Теперь вы знаете как посмотреть запущенные службы linux, идем дальше.

Чтобы запустить службу используется команда start, например:

sudo systemctl start application.service

Причем расширение service можно опустить, оно и так подставляется по умолчанию. Если запуск прошел хорошо, программа ничего не выведет.

Остановить службу linux можно командой:

sudo systemctl stop application

Посмотреть состояние службы позволяет команда status:

sudo systemctl status application

Здесь вы можете видеть, состояние running, exited, dead, failed и т д. А также несколько последних строчек вывода программы, которые очень помогут решить проблему с запуском если она возникнет.

Автозагрузка служб в systemd

Как вы знаете, systemd позволяет автоматически загружать службы при запуске системы по мере их надобности. Команда list-unit-files показывает добавлена ли служба в автозагрузку.

Вообще, здесь может быть несколько состояний — enabled — в автозагрузке, disabled — автозагрузка отключена, masked — служба скрыта и static — значит что служба в автозагрузке, но вы не можете ее отключить.

Поэтому чтобы получить список служб linux, запускаемых автоматически достаточно отфильтровать ее вывод по состоянию:

systemctl list-unit-files —state enabled

Все службы, запускаемые по умолчанию. Можете также посмотреть службы static. Чтобы добавить службу в автозагрузку linux используйте команду enable:

sudo systemctl enable application

А для того чтобы убрать ее из автозагрузки:

sudo systemctl disable applciation

Также, вы можете посмотреть разрешена ли сейчас автозагрзука для службы:

sudo systemctl is-enabled application

Утилита просто выведет состояние enabled, disabled или static.

Выводы

Теперь настройка служб Linux не вызовет у вас проблем. Много чего мы упустили, systemd — очень большая, сложная и многофункциональная система, которую не охватить в одной статье. Но и также очень сложно понять. Но я думаю, что все, что касается управления службами Linux мы разобрали. Если у вас остались вопросы, спрашивайте в комментариях!

Источник

Оцените статью