Как посмотреть запущенные сервисы в linux
Перейти к содержимому

Как посмотреть запущенные сервисы в linux

  • автор:

How To find Linux list running services under Systemd

To get all running services under systemd on Linux, run and list systemctl services. You’ll find a list of all the services on your system. The list systemctl command stores configuration files in the System unit and the User unit in specific directories. If you’re unfamiliar with the list services systemctl, use the pkg-config systemd command to determine which directories hold your systemd configuration files.So, in this tutorial I’m going to show you how to deal with commands to list processes under Linux.

Linux operating system offers many management options (start, stop and restart, enabling auto-start at boot, etc.). A process manager typically manages services, and most modern Linux distributions use the systemd process manager.

Systemd is a Linux system and service manager. It is compatible with SysV init scripts, LSB init scripts, and the systemctl command.

Table of Contents

List All Services Under Systemd

List All Running Services Under Systemd in Linux

To find out what’s active running on your Linux operating system, you need to run a command called listing services under SystemD. The systemd daemon loads unit files that run services on the system. Listing active services is essential for ensuring that your system is secure. By learning about systemctl list available processes under SystemD, you can reduce the risk of security issues and exploitation. Here are some tips to help you.

The systemctl linux command can be run without any arguments. It will display all systemd units loaded (read the systemd documentation to learn more about systemd units), along with processes and their status (active or inactive).

You can get all loaded services in your system, whether running, exiting, or active. Use the list-units subcommand and the –type switch with a value for service.

You can also add the –state option to get all active but loaded services (both running and exited).

Run the following command to get a quick overview of all active services, i.e., all loaded.

To make it easier to invoke the above command, create an alias command in your file.

Add the following line to the list of aliases, as shown in the screenshot.

Close the file, save the changes and close it. To view a complete list of active services loaded on your dedicated server, you can use the ” Running_Services” command.

Ports are also important aspects of processes. You can use the Netstat and SS tools to determine which port the daemon process is listed to.

Flag -l stands for print all listening sockets. -u displays all TCP connections. -t shows all TCP connections. -n prints numeric port numbers. -p is shown the application name.

The fifth column displays the socket: Local address: Port. The process Zabbix_agentd listens on port 10050.

You can also list the services and ports that were opened by the firewall on your server using the firewall-cmd or ufw linux command, depending on which Linux distribution you’re using.

Systemd list all services

You can also use systemd list all services to list-unit-files and see the list of all unit files. If your terminal supports underlining, you’ll see that the unit’s header will be highlighted. If a service fails to start, a colored dot will appear in its place. Units are representations of systemd resources. The state of each unit is shown in the LOAD, ACTIVE, and SUB columns. The list is not permanent, and new systemd releases may add or remove values.

how to list all services in linux?

If you want to know which processes are currently active on your computer, you can use the command systemd list all services to see which processes are active. This command lists the unit load active of all systemd services and their states. You can filter the output by type and state to view only the active units, and the state of the processes will filter the output. This can be helpful for troubleshooting issues with systemd.

list all services Red Hat / CentOS

If you are using CentOS on your system, you should use the right command to get all active services. This command is called a systemd status command, and in CentOS, the status command is available in all shells.
Of course, the list of services depends on the system’s running software or process.

So, here is the command:

To get all active processes, just run the following command:

list all services Ubuntu / Debian

You may need all the active services when using an Ubuntu Linux distribution. Some services are system processes, while others are just system logins. Knowing which ones are running is essential for system administrators, and Ubuntu has a command that allows you to see which processes are currently active. If you are using Ubuntu as your primary operating system, you should be able to use this command to get all of the services on your system.
So, here is the exact ubuntu command to get all services:

Systemd usage purpose

You can use the list services linux systemctl command to find which services are active on your system. If you want to see which processes are currently active on your system, you can specify which options you’d like to use. By default, the list shows active services only. However, you can specify all processes or just the ones that are currently active.

When it comes to Linux operating system, you might be wondering how to check your Systemd service status. Thankfully, systemd is present on most of the major Linux distributions. This systemd service is responsible for controlling the processes that run on a system. You can use systemd to start and stop any process you wish and view its status.

Use Systemctl to Check If Service Is Not Running

The command systemctl check if the service is not running can be a good way to find out what’s wrong with your system. This command line can show you your processes’ most recent log entries. You can also see the logs of any dependency services that your system might use to run. If a process depends on another, you can disable it to prevent it from starting automatically on the next system restart.

Conclusion

You’re probably wondering, Why should I use Systemctl? Well, this command line is used to manage services. It can also help you troubleshoot slow-booting servers. The output from systemctl can be used to troubleshoot individual services, too.

How To List Services on Linux

As a system administrator, you are probably dealing with a lot of services every day.

On Linux, services are used for many different purposes.

They may be used in order to start a SSH server on your machine or they can perform some operations on a specific hour or day.

Whether you are using a Debian based distribution or a RedHat one, querying services is very similar.

However, given the distribution you are using, and more specifically the initialization system (init or systemd), you may have to use different commands.

In this tutorial, you will learn how you can, given your system manager, list all services on your Linux machine.

Table of Contents

Determine the system manager used

As you probably know, recent distributions use the Systemd system manager.

However, it has not always been the case : in the past, most distributions used the SysVinit system manager.

As a consequence, there are really two ways of managing your services on a Linux system.

Before learning the commands to list services, you have to know the system manager that you are currently using.

To determine your current system manager, the easiest way is to use the “pstree” command and to check the first process ever run on your system.

pstree command on linux

If you see “systemd“, it obviously means that you are currently using systemd. However, if you see “init“, it means that you are using SysVinit.

On Ubuntu 14.04, that is still using the old init system, your “pstree” may look like this.

pstree init system

List Services using systemctl

The easiest way to list services on Linux, when you are on a systemd system, is to use the “systemctl” command followed by “list-units”. You can specify the “–type=service” option in order to restrict the results to services only.

list active services on linux

By default, this command will show you only the services that are active or the services that have failed on your system. In the screenshot above, most of the services are active but the logrotate one (highlighted in red) is marked as failed.

Awesome, you learnt how you can easily list your services on a Linux server.

However, as you may have noticed, you did not have access to all services : what about inactive services? What about services that were not loaded by systemd on boot?

List All Services on Linux using list-units

In order to list all services, meaning active and inactive, you have to use the “systemctl list-units” command followed by the “–all” option.

Similarly, you can limit the results to services only by using the type filter.

list inactive services linux

As you can see, inactives services also listed which might be convenient if you just wrote your service and looking after it in the list.

In this case, only loaded services are listed. On boot, systemd loads unit files and it may choose not to load a specific service if it finds that it won’t be used by the system.

As a consequence, there is a real difference between “loaded” and “installed” services. “Installed” services mean that unit files can be found in the corresponding paths.

service path systemd

List Services By State

In some cases, you may only be interested in services that have failed. For that, you can specify the state that you are looking for as an option of the systemctl command.

Where “state” can be one of the following values : active, inactive, activating, deactivating, failed, not-found or dead.

For example, if we are only interested in “failed” services, we are going to run the following command

list failed services on ubuntu

List All Service Files using list-unit-files

Finally, if you are interested in “loaded“, “installed“, “disabled” as well as “enabled” service files, there is a another command that might be pretty handy.

In order to list all service files available, you have to use the “systemctl” command followed by “list-unit-files”. Optionally, you can specify the type by using the “–type=service” option.

list installed services

Alternatively, you can use the “grep” command in order to search for specific paths on your system that may contain service files.

Congratulations, you learnt how you can list services if your system is using systemd!

List Services using service

The easiest way to list services on Linux, when you are on a SystemV init system, is to use the “service” command followed by “–status-all” option. This way, you will be presented with a complete list of services on your system.

listing services on init systems

As you can see, each service is listed preceded by symbols under brackets. Those symbols mean :

  • + : means that the service is running;
  • : means that the service is not running at all;
  • ? : means that Ubuntu was not able to tell if the service is running or not.

So why are some services to tell if they are running or not, and some are not able to?

It all comes down to the implementation of the init script. In some scripts, such as the udev script for example, you are able to see that the “status” command is implemented.

This is not the case for the “dns-clean” script for example which is the reason why you have a question mark when you query this service.

List SysVinit Services in Folders

Another way of listing the current list of services is to use the “ls” command on the folders containing all scripts on a Linux system, namely “/etc/init.d”.

listing init scripts

Conclusion

In this tutorial, you learnt how you can easily list services on a Linux system whether you are using systemd or SysVinit ones.

If you are interested in creating your own services, we recommend that you have a look at the following resources. They might be really useful in order to correctly achieve that.

If you are interested in Linux System Administration, we have a complete section on this subject on the website, so make sure to check it out.

Listing Linux Services With Systemctl

A variety of services run continuously on a Linux background, such as network and system services. Services running on Linux are also known as daemons, which refers to a group of processes working on the back-end.

Services can be managed and listed through different methods and tools. The Systemd is a software suite of tools with the ability to manage Linux systems adopted by Linux distribution as a drop-in replacement of the init process.

All system tasks can be controlled through Systemd. The process can be started or ended using this tool, and all enabled and disabled services information can also be listed with Systemd.

List Services Using Systemctl in Linux

Systemctl is a utility with the responsibility to manage and control the systemd system. The systemctl command can be used to list all services in Linux.

We will now show you how systemctl works.

List All Services

To get a list of all the services on the system, whether they are loaded or inactive, issue the following systemctl command in the terminal:

All services in your system will appear on the screen, as you can see in the output shown in the image above.

List Loaded Services

The following command will list every loaded service that is running, active, or failed:

Running Services

In many cases, it can be difficult to distinguish the running services from all the other services. Run the following command to obtain a quick response that shows the loaded and running services in the system:

Enabled Services

Enter the following command to check the enabled services in the system:

Disabled Services

Disabled services will not start up or activate automatically. To enable a desired/required service, select the service from the disabled category. The following command is used to obtain a list of the disabled services in the system:

Check Service Status

The “cup” command is used to obtain more information about the status of a service. Cup is a modular printing system through which the computer acts as a print server and displays information. Use the cups command to obtain more information about the enabled/disabled services in the system:

Where are systemctl service files

Systemd configuration files are stored in specific directories. There are System unit directories and User unit directories.

You can find the location of the System Unit and User Unit directories using the pkg-config systemd command.

Run the following commands to find the directories on your system:

$ pkg-config systemd —variable =systemdsystemunitdir

$ pkg-config systemd —variable =systemduserunitdir

You can browse to these directories and see the systemd unit files.

Conclusion

This article showed you how to use systemctl commands to list services in Linux, including multiple options for viewing the services. With the correct knowledge, it is easy to pick the required command.

About the author

Syeda Wardah Batool

I am a Software Engineer Graduate and Self Motivated Linux writer. I also love to read latest Linux books. Moreover, in my free time, i love to read books on Personal development.

Список служб Linux с помощью Systemctl

В Linux служба — это программа, работающая в фоновом режиме . Службы можно запускать по запросу или во время загрузки.

Если вы используете Linux в качестве основной операционной системы или платформы разработки, вы будете иметь дело с различными службами, такими как веб-сервер, ssh или cron . Знание того, как перечислить запущенные службы или проверить статус службы, важно при отладке системных проблем.

Большинство последних дистрибутивов Linux используют systemd в качестве системы инициализации и диспетчера служб по умолчанию.

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

В этой статье объясняется, как составить список служб в Linux.

Список служб Linux

Systemd использует концепцию модулей, которыми могут быть службы, сокеты, точки монтирования, устройства и т. Д. Модули определяются с помощью текстовых файлов в формате ini . Эти файлы содержат информацию об устройстве, его настройках и командах для выполнения. Расширения файлов определяют тип файла модуля. Например, файлы системных сервисных модулей имеют расширение .service .

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

Чтобы получить список всех загруженных служебных единиц, введите:

Каждая строка вывода содержит следующие столбцы слева направо:

  • UNIT — Название сервисной единицы.
  • LOAD — Информация о том, загружен ли файл объекта в память.
  • ACTIVE — состояние активации файла модуля высокого уровня, которое может быть активным, перезагружающимся, неактивным, неудачным, активируемым, деактивируемым. Это обобщение столбца SUB .
  • SUB — состояние активации файла юнита низкого уровня. Значение этого поля зависит от типа объекта. Например, модуль типа service может находиться в одном из следующих состояний: неработающий, завершенный, сбойный, неактивный или работающий.
  • DESCRIPTION — Краткое описание файла объекта.

По умолчанию команда перечисляет только загруженные активные юниты. Чтобы увидеть загруженные, но неактивные модули, передайте параметр —all :

Если вы хотите увидеть все установленные файлы модулей, а не только загруженные, используйте:

Отображение статуса службы

Чтобы проверить статус службы, используйте команду systemctl status :

Где <service_name> — это имя сервисной единицы, которую вы хотите проверить. Например, чтобы определить текущий статус службы nginx, вы должны запустить:

Команда напечатает следующую информацию:

  • Loaded — Loaded ли служебный модуль и полный путь к файлу модуля. Он также показывает, разрешен ли запуск устройства во время загрузки.
  • Active — активна и работает ли служба. Если ваш терминал поддерживает цвета, а служба активна и работает, точка ( ● ) и часть «активен (работает)» будут напечатаны зеленым цветом. Строка также показывает, как долго работает служба.
  • Docs — служебная документация.
  • Process — информация о процессах обслуживания.
  • Main PID — сервисный PID.
  • Tasks — количество задач, учитываемых для объекта, и лимит задач.
  • Memory — информация об используемой памяти.
  • CGroup — информация о связанных контрольных группах.

Если вы хотите только проверить статус службы, используйте команду systemctl is-active . Например, чтобы убедиться, что служба nginx запущена, вы должны запустить:

Команда покажет вам статус службы. Если служба активна, команда возвращает статус выхода 0, что может быть полезно при использовании команды внутри сценариев оболочки.

Выводы

Мы показали вам, как использовать команду systemctl для systemctl списка служб Linux и проверки их статуса.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии ниже.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *