Linux what is masked service

How to Control (start/stop/mask/unmask) Services Using Systemd

Services need to be stopped or started manually for a number of reasons: perhaps the service needs to be updated; the configuration file may need to be changed; or a service may need to be uninstalled, or an administrator may manually start an infrequently used service.

To start a service, first verify that it is not running with systemctl status. Then, use the systemctl start command as the root user (using sudo if necessary). The example below shows how to start the sshd.service service:

[[email protected] ~]# systemctl start sshd.service 

The systemd service looks for .service files for service management in commands in the absence of the service type with the service name. Thus the above command can be executed as:

To stop a currently running service, use the stop argument with the systemctl command. The example below shows how to stop the sshd.service service:

[[email protected] ~]# systemctl stop sshd.service 

Restarting and Reloading Services

During a restart of a running service, the service is stopped and then started. On the restart of service, the process ID changes and a new process ID gets associated during the startup. To restart a running service, use the restart argument with the systemctl command. The example below shows how to restart the sshd.service service:

[[email protected] ~]# systemctl restart sshd.service 

Some services have the ability to reload their configuration files without requiring a restart. This process is called a service reload. Reloading a service does not change the process ID associated with various service processes. To reload a running service, use the reload argument with the systemctl command. The example below shows how to reload the sshd.service service after configuration changes:

[[email protected] ~]# systemctl reload sshd.service 

In case you are not sure whether the service has the functionality to reload the configuration file changes, use the reload-or-restart argument with the systemctl command. The command reloads the configuration changes if the reloading functionality is available. Otherwise the command restarts the service to implements the new configuration changes:

[[email protected] ~]# systemctl reload-or-restart sshd.service 

Listing Unit Dependencies

Some services require that other services be running first, creating dependencies on the other services. Other services are not started at boot time but rather only on demand. In both cases, systemd and systemctl start services as needed whether to resolve the dependency or to start an infrequently used service. For example, if the CUPS print service is not running and a file is placed into the print spool directory, then the system will start CUPS-related daemons or commands to satisfy the print request.

[[email protected] ~]# systemctl stop cups.service Warning: Stopping cups, but it can still be activated by: cups.path cups.socket 

To completely stop printing services on a system, stop all three units. Disabling the service disables the dependencies. The ‘systemctl list-dependencies UNIT’ command displays a hierarchy mapping of dependencies to start the service unit. To list reverse dependencies (units that depend on the specified unit), use the –reverse option with the command.

[[email protected] ~]# systemctl list-dependencies sshd.service sshd.service ● ├─system.slice ● ├─sshd-keygen.target ● │ ├─[email protected] ● │ ├─ss[email protected] ● │ └─[email protected] ● └─sysinit.target . output omitted. 

Masking and Unmasking Services

At times, a system may have different services installed that are conflicting with each other. For example, there are multiple methods to manage mail servers (postfix and sendmail, for example). Masking a service prevents an administrator from accidentally starting a service that conflicts with others. Masking creates a link in the configuration directories to the /dev/null file which prevents the service from starting.

[[email protected] ~]# systemctl mask sendmail.service Created symlink /etc/systemd/system/sendmail.service → /dev/null. 
[[email protected] ~]# systemctl list-unit-files --type=service UNIT FILE STATE sendmail.service masked . output omitted. 

Attempting to start a masked service unit fails with the following output:

[[email protected] ~]# systemctl start sendmail.service Failed to start sendmail.service: Unit sendmail.service is masked 

Use the systemctl unmask command to unmask the service unit.

[[email protected] ~]# systemctl unmask sendmail Removed /etc/systemd/system/sendmail.service. 

Note: A disabled service can be started manually or by other unit files but it does not start automatically at boot. A masked service does not start manually or automatically.

Читайте также:  Чем запустить installer linux

Enabling Services to Start or Stop at Boot

Starting a service on a running system does not guarantee that the service automatically starts when the system reboots. Similarly, stopping a service on a running system does not keep it from starting again when the system reboots. Creating links in the systemd configuration directories enables the service to start at boot. The systemctl commands create and remove these links.

To start a service at boot, use the systemctl enable command.

[[email protected] ~]# systemctl enable sshd.service Created symlink /etc/systemd/system/multi-user.target.wants/sshd.service → /usr/ lib/systemd/system/sshd.service. 

The above command creates a symbolic link from the service unit file, usually in the /usr/lib/systemd/system directory, to the location on disk where systemd looks for files, which is in the /etc/systemd/system/TARGETNAME.target.wants directory. Enabling a service does not start the service in the current session. To start the service and enable it to start automatically during boot, execute both the systemctl start and systemctl enable commands.

To disable the service from starting automatically, use the following command, which removes the symbolic link created while enabling a service. Note that disabling a service does not stop the service.

[[email protected] ~]# systemctl disable sshd.service Removed /etc/systemd/system/multi-user.target.wants/sshd.service. 

To verify whether the service is enabled or disable, use the systemctl is-enabled command.

Summary of systemctl Commands

Services can be started and stopped on a running system and enabled or disabled for an automatic start at boot time.

Useful Service Management Commands:

TASK COMMAND
View detailed information about a unit state. systemctl status UNIT
Stop a service on a running system. systemctl stop UNIT
Start a service on a running system. systemctl start UNIT
Restart a service on a running system. systemctl restart UNIT
Reload the configuration file of a running service. systemctl reload UNIT
Completely disable a service from being started, both manually and at boot. systemctl mask UNIT
Make a masked service available. systemctl unmask UNIT
Configure a service to start at boot time. systemctl enable UNIT
Disable a service from starting at boot time. systemctl disable UNIT
List units required and wanted by the specified unit. systemctl list-dependencies UNIT
Читайте также:  Linux timezone asia yekaterinburg

Источник

Замаскированные службы Linux.

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

Службу вы установили, и уверены, что она работает правильно, но каким-то образом вы больше не можете контролировать ее. Вы никак не можете этим управлять. Так что же случилось?

Скорее всего, кто-то замаскировал вашу службу. Маски — это один из способов отключения службы. В случае, когда вы отключаете службу с помощью sudo systemctl disabled , все символические ссылки для службы удаляются. При маскировании службы символические ссылки перемещаются и указывают на /dev/null. Когда вы просто отключаете службу, ее все равно можно запустить вручную командой start. Когда вы маскируете службу, ее нельзя запустить вручную. Другими словами, маскирование службы делает ее непригодной для использования до тех пор, пока она не будет демаскирована.

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

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

Выполните приведенную выше команду, и вы, вероятно, удивитесь, сколько служб замаскировано в вашей системе. Я обнаружил пару замаскированных сервиса в своей системе, одним из которых был mysql.service. Если я хочу использовать MySQL на этой машине, мне придется сначала размаскировать службу.

Как замаскировать службу в Linux.

Первое, что мы сделаем, это научимся маскировать службу в Linux. Возьмем к примеру службу MySQL. Откройте окно терминала и замаскируйте службу MySQL с помощью команды:

Читайте также:  Space cadet pinball linux

Если вы не маскировали службу MySQL до этого, теперь она будет отображаться в выводе команды systemctl list-unit-files | grep masked. На данный момент служба MySQL не может запускаться ни автоматически, ни вручную. Попробуйте запустить службу командой:

Вы должны будете увидеть следующую ошибку:

Как размаскировать службу в Linux.

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

Теперь, когда вы запустите MySQL, он будет работать, как обычно.

Вот и все, что вам нужно знать для управления замаскированными службами в Linux. Надеюсь кому-то пригодится.

А если Вам понравилась статья, то подписывайтесь на мой канал дзен (кнопка ниже), либо в telegramm и ВКонтакте . Так же не забудьте про мой сайт RoadIT , в котором я потихоньку собираю материал, знание которого приведет вас в мир IT.

Источник

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