- How to Manage and List Services in Linux
- Linux Services
- How to List Services in Linux
- Managing Linux Services
- Conclusion
- Systemd: пишем собственные .service и .target
- Чего я хотел?
- Что я сделал?
- Что такое service?
- Что такое target?
- Как я это сделал?
- Какие были проблемы?
- Результат
- Cheat sheet
- How to check all running services in Linux
- Method-1: Listing Linux Running Services with service command
- Method-1(a): How to check running services in System V (SysV) init System
- Method-1(b): How to check running services in Linux with pstree command
- Method-2: How to check running services in systemd system using the systemctl command
- Method-2(a): Listing Linux services with pstree command
- Method-2(b): Listing Linux Services with chkservice command
- Conclusion
How to Manage and List Services in Linux
Managing a Linux VPS is a critical and sometimes very difficult task if you don’t have the right tools. Often the difficulty lies in having to configure and maintain many resources and services. On a server, most resources are software making them a little easier to monitor. In this tutorial, you’ll learn all the Linux service basics, including how to manage, control, and list services in Linux.
Linux Services
A service is a program that runs in the background outside the interactive control of system users as they lack an interface. This in order to provide even more security, because some of these services are crucial for the operation of the operating system.
On the other hand, in systems like Unix or Linux, the services are also known as daemons. Sometimes the name of these services or daemons ends with the letter d. For example, sshd is the name of the service that handles SSH.
So, let us start to work and list services in Linux.
How to List Services in Linux
Let’s look at a potential scenario. While running your Linux system, you can no longer access localhost. Chances are that the HTTP service was disabled, and causing the problem.
To troubleshoot issues like this one and many others, it’s good to know how to list all services in Linux.
Fortunately, CentOS and Ubuntu – two of the most popular operating systems in their areas – share systemd. That means that the commands we are going to present are compatible with both systems.
First, we have to connect to our server using SSH. If you’re having trouble, check out our PuTTY tutorial.
Once inside, we need to be the root user to list service in Linux.
Now we can list all services in Linux. To do it, run the command:
When the command is run, we will see all the services that are on the system. However, we will also see that some have a defined status. Let’s learn what all these mean.
- Enabled services are currently running. They usually have no problems.
- Disabled services are not active but can be activated at any time without a problem.
- Masked services won’t run unless we take that property away from them.
- Static services will only be used in case another service or unit needs it.
- Finally, there are services generated through a SysV or LSB initscript with systemd generator.
In case we want to know only the services that are active, we have to use a command together with grep, like so:
Managing Linux Services
Now it is time to learn how to manage a specific service. Note that each service represents software that works differently. In this tutorial, we will only show how to start, check the status of and stop services – the basic controls
To start a service on Linux, we need to run the following command:
If the service is correctly configured, it will start. Now, if we want to stop it, we will use the following command:
Meanwhile, to check the status of a service we can use:
It is also possible to have a service run while the operating system is being loaded:
Or remove it from the initial load:
Finally, it is possible to verify which port is being used by a service. For this, we will use netstat.
To install it on Ubuntu, we just run:
If we are using CentOS 7:
Then, we run the following command:
The output will give us all the required network information.
Conclusion
Learning how to list services in Linux is easy and can greatly speed up troubleshooting! In this tutorial, we learned how to start, enable, disable, stop, and list all services in Linux! Now you can manage your Linux VPS like a pro.
Finally, we recommend you to read more about systemctl to learn all the in-depth uses. Happy developing!
Edward is an expert communicator with years of experience in IT as a writer, marketer, and Linux enthusiast. IT is a core pillar of his life, personal and professional. Edward’s goal is to encourage millions to achieve an impactful online presence. He also really loves dogs, guitars, and everything related to space.
Источник
Systemd: пишем собственные .service и .target
У меня появился Linux на домашнем компьютере, и я поспешил обжиться в новой ОС. Она была установлена с systemd init process. Это было мое первое знакомство с этим новым инструментом. Cвой ноутбук я использую для каждодневной жизни и для программирования. Мне хотелось включать рабочие программы (Apache2 и MySQL) только на время, пока я их использую, чтобы не тратить впустую ресурсы своего компьютера. Дополнительно, для тестирования я написал bash скрипт, который выгружает содержимое одной из MySQL БД c жесткого диска в ОЗУ (в tmpfs) – так тесты выполняются значительно быстрее. По идее, я мог бы начинать свой рабочий день вот так:
И заканчивать его:
Но мне хотелось сделать вещи “как надо”.
Чего я хотел?
Я хотел достичь 2 целей:
- Мне было лень писать 2 команды (запуск apache и запуск mysql), т.к. я знал, что обе программы всегда будут выключаться и включаться синхронно. Хотелось выполнять эту операцию одной командой.
- Дело попахивало неприятностями, если компьютер перезагрузится пока моя база данных будет сидеть в tmpfs – все файлы будут потеряны. Конечно, я делал бекапы, но мне опять же было лень восстанавливать их вручную после каждой непредвиденной перезагрузки.
Что я сделал?
В итоге я объединил Apache2 и MySQL в один target. Это позволило запускать оба сервиса одной командой. А свой mysqld-tmpfs скрипт я декларировал в виде сервиса в глазах systemd. Будучи сервисом, я уверен, что systemd выполнит его корректную остановку, если система пойдет на перезагрузку или еще в какую-то нештатную ситуацию, и моя БД без потерь сохранится на жесткий диск.
Что такое service?
Это некоторая программа, которая выполняется в фоне и предоставляет полезную функциональность. К примеру, Apache веб сервер. Сервисы можно запускать и останавливать. Некоторые сервисы могут запускаться и останавливаться автоматически по определенным событиям (загрузка ОС, выгрузка ОС и тп). Так же их можно запускать/останавливать вручную. Сервис декларируется в /etc/systemd/system/my-name.service файлах (с суффиксом “.service”).
Что такое target?
Target в systemd очень похож на runlevel в openRC, но это все-таки разные вещи. Во-первых, target позволяет группировать 1 и более сервисов в единый блок. Группируя сервисы в targets, ими проще управлять. Во-вторых, systemd автоматически включает/выключает targets по событиям. “Включение” target означает включение всех сервисов, которые он объединяет в себе. К примеру, если в systemd настроен target по умолчанию my-favorite.target, то при загрузке системы systemd включит все сервисы, которые задекларированы внутри my-favorite.target. В какой-то момент в консоли можно набрать:
Все сервисы из my-another.target будут включены, и все включенные сервисы не из my-another.target будут выключены. Это очень похоже на переключение runlevel в openRC. Однако, systemd поддерживает включение более чем 1 target. Вот пример:
После выполнения этих команд в системе будет работать объединение сервисов из my-favorite.target и my-another.target.
Как я это сделал?
В итоге у меня получился вот такой mysqld-tmpfs.service файл:
И вот такой programming.target файл:
Какие были проблемы?
При остановке programming.target почему-то нижележащие apache2.service и mysqld.service не останавливались. Почитав как следует man page, я нашел проблему: systemd останавливает сервисы “лениво” — если никто не требует запущенный сервис, и он не был запущен явным образом, а как зависимость для какого-то другого сервиса, то systemd остановит его только при одном из 3 обстоятельств:
- Запустится какой-то другой сервис, который в своей декларации указывает, что он конфликтует с нашим сервисом.
- Выполнится systemctl isolate some-another.target или systemctl stop this.service.
- Наш сервис может запросить в своей декларации останавливать себя не ленивым образом, а активным, добавив вот такую строку в [Unit] секцию: StopWhenUnneeded=true
Декларации “чужих” сервисов можно менять создавая файлы /etc/systemd/system/name-i-alter.service.d/*.conf. Я просто создал /etc/systemd/system/apache2.service/auto-stop.conf и /etc/systemd/system/mysqld.service.d/auto-stop.conf и поместил туда ту строку.
Другая проблема, на которую я, наткнулся была в том, что systemd не очень любит symlinks. Я не большой любитель “загаживать” системные директории типа /etc, /bin, /usr своими локальными продуктами жизнедеятельности, поэтому изначально я попытался свой /etc/systemd/system/mysqld-tmpfs.service сделать symlink на /root/scripts/mysqld-tmpfs.service файл, т.е. хранить сам файл в домашнем каталоге root пользователя. Но systemctl команда отказывалась работать с таким сервисом выдавая малопонятные ошибки. Оказалось, что определенную часть своей внутренней кухни systemd делает именно на symlinks, и ему тогда “трудно” отличать внутреннюю кухню (свои symlinks) от сторонних *.service файлов (если они тоже являются symlinks). Удалив symlink из /etc/systemd/system/mysqld-tmpfs.service и скопировав туда содержимое настоящего файла, я решил эту проблему. Более подробное описание этой проблемы можно прочитать тут: bugzilla.redhat.com/show_bug.cgi?id=955379
Результат
Я достиг своей цели. Начиная рабочий день:
Когда нужно выполнить тесты на своем проекте:
Когда я хочу демонтировать БД из tmpfs в жесткий диск (хотя на практике я так почти не делаю, а просто оставляю БД в tmpfs на целый день, и при выключении systemd за меня запускает демонтировку из tmpfs в жесткий диск):
Когда я закончил работать и хочу остановить рабочие программы:
Cheat sheet
Некоторые полезности при работе с systemd:
- Вызывайте systemctl daemon-reload, если вы изменили декларацию чего-либо (systemd считает файлы декларации заново)
- systemctl start my-name.(service|target) – запуск сервиса или target
- systemctl stop my-name.(service|target) – остановка сервиса или target
- systemctl enable my-name.service – сервисы могут декларировать при каких включенных targets они должны включаться. Для этого используется [Install] секция в файле декларации сервиса. Вы, как сисадмин, имеете власть на установку этого “пожелания” сервиса. Часто сервисы “устанавливаются” в target по умолчанию multi-user.target или в похожее.
- systemctl disable my-name.service – обратная операция по отношению к enable: деассоциировать связь между my-name.service и targets, которые он запросил в [Install] секции своей декларации.
- systemctl isolate my.target — включить все сервисы из my.target и выключить все остальные включенные сервисы.
- systemctl status my-name.(service|target) — узнать статус (запущен/остановлен) у сервиса или target.
Надеюсь, эта статья кому-то поможет при осваивании systemd. Я попытался сделать ее компактной, и если упустил из внимания какие-то дополнительные вопросы, спрашивайте в комментариях!
Источник
How to check all running services in Linux
There are many ways as well as tools to check and list all running services in Linux.
Most Linux administrators typically use ‘service service_name status’ or ‘/etc/init.d/service_name status’ for the System V (SysV) init system, and ‘systemctl status service_name’ for the systemd systems for a specific service.
The above commands show whether the particular service is running on the server or not. These are frequently used commands by every Linux administrator.
If you are new to the environment and want to know what services are running on the system, continue to read.
The following commands lists all the services running on the system and give you an idea of what purpose the system is being used for. Also, it provides an opportunity to disable certain services that are not used on the system.
‘init’ (short for initialization) is the first process started during booting of the computer system. init is a daemon process that continues running until the system is shut down.
We recommend reading the following articles related to this topic.
Many init systems have been developed for Linux, but the following are the three most familiar and commonly used init systems.
- System V (Sys V) is the older init system
- Upstart is an event-based replacement for the traditional init system
- systemd is the new init system, that was adopted by most of the latest Linux distributions
Method-1: Listing Linux Running Services with service command
To display the status of all available services at once in the System V (SysV) init system, run the service command with the —status-all option:
If you have multiple services, use file display commands (like less or more) for page-wise viewing. The following command will show the below information in the output.
- Running services and their associated PID
- Stopped services
- Configured iptables rules
- Configured and active network interface information.
Run the following command to see only running services in the system.
Run the following command to see the specified service status. For instance, use the following command to check the Apache Web server status on a RHEL based system.
To determine the current status of a particular service, execute the following command.
Use the following command to see a list of services that were enabled on boot. These services will be kicked on as part of the system boot process.
Method-1(a): How to check running services in System V (SysV) init System
Alternatively, you can view services running on a Linux system by issuing the ‘initctl’ command as shown below.
Method-1(b): How to check running services in Linux with pstree command
Run the ‘pstree’ command without any additional parameter to see services running in the Linux system:
Method-2: How to check running services in systemd system using the systemctl command
‘systemctl’ command allows users to check and list all services running in a Linux system that uses “systemd” as the system manager.
- UNIT Describe about the corresponding systemd unit name.
- LOAD Describes whether the corresponding unit currently loaded in memory or not.
- ACTIVE Indicate whether the unit is active or not.
- SUB Indicate whether the unit is in running state or not.
- DESCRIPTION A short description about the unit.
To see loaded service in the system, use the list-units subcommand and the —type switch with a value of service. It shows active, running, exited or failed services in the output.
Run the following command to view a particular service status.
Detailed information about a particular service can be verified with the systemctl command as shown below.
Run the following command to view the services running on the system with the systemctl command:
Use the below command to see which services were enabled on boot:
systemd-cgtop shows top control groups by their resource usage such as tasks, CPU, Memory, Input, and Output:
Method-2(a): Listing Linux services with pstree command
List of services running in a Linux system can be verified using the ‘pstree’ command as shown below.
Method-2(b): Listing Linux Services with chkservice command
chkservice is a new tool for managing systemd units in terminal. It requires super user privileges to manage the units.
To view the help page, hit ‘?’ button. This will show you available options to manage the systemd services.
Conclusion
This article explained several ways to check and list all running Linux services.
If you have any questions or feedback, feel free to comment below.
Источник