Disabling services in linux

Как отключить ненужные службы в Linux

Когда мы настраиваем сервер, необходимо спросить себя, что нам действительно необходимо. Нужен ли нам веб-сервер или FTP-сервер, NFS-сервер или DNS-сервер, сервер базы данных или что-то другое.
В этой статье мы поговорим о некоторых ненужных приложениях и службах, которые могут быть вам без надобности, но устанавливаются по умолчанию при инсталляции системы и незаметно потребляют ваши системные ресурсы.

Сначала давайте посмотрим, какие службы работают в системе:

Теперь посмотрим на процессы, которые подключаются к портам, это можно сделать с помощью команды netstat:

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

1. smbd и nmbd

smbd и nmbd — это демон Samba Process. Действительно ли вам нужно предоставлять общий доступ к ресурсам для машин, работающих под windows? Если нет, почему эти процессы работают? Вы можете их безопасно завершить и убрать из автозагрузки.

2. Telnet

Нужна ли вам связь по протоколу Telnet (bidirectional interactive text-oriented communication) в интернете или в локальной сети? Если нет, завершайте этот процесс и исключайте его из автозагрузки.

3. rlogin

Требуется вам авторизация на удаленной машине по сети? Если нет, завершаем этот процесс и убираем из автозагрузки.

4. rexec

Remote Process Execution или rexec позволяет вам выполнять команды оболочки на удаленном компьютере. Если вам это не нужно, просто завершите процесс.

5. FTP

Вы передаете файлы через интернет? Если нет, эту службу спокойно можно отключить.

6. automount

Вам нужно автоматически монтировать различные файловые системы, чтобы подключить сетевую файловую систему? Если нет, почему этот процесс работает? Завершите процесс и уберите его из автозагрузки.

7. named

Вам нужен запущенный DNS-сервер? Тогда что мешает вам освободить занимаемые им системные ресурсы. Завершите процесс и уберите его из автозагрузки.

8. lpd

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

9. Inetd

Используете ли вы какие-нибудь службы inetd? Если вы запускаете отдельное приложение, такое как ssh, которое в свою очередь использует другое отдельное приложение, например Mysql, Apache и так далее, то вам не нужен inetd. Лучше отключить его автоматическую загрузку.

10. portmap

Portmap — это Open Network Computing Remote Procedure Call (ONC RPC), использующий демоны rpc.portmap и rpcbind. Если у вас работают эти процессы, значит запущен NFS-сервер. В противном случае ваши системные ресурсы расходуются напрасно.

Как завершить процесс в Linux

Для того, чтобы завершить работающий процесс в Linux, используется команда «Kill PID». Но сначала нам необходимо узнать PID процесса. Например, я хочу узнать PID процесса «cupsd»:

Итак, PID процесса cupsd 1511. Для того, чтобы завершить этот процесс, используем команду:

Как отключать службы в Linux

В дистрибутивах на базе Red Hat, таких как Fedora и CentOS для отключения и включения служб используется скрипт «chkconfig».
Например, давайте отключим автозагрузку сервера Apache:

В дистрибутивах на базе Debian, таких как Ubuntu, Linux Mint, для этой цели используется скрипт update-rc.d.
Например, для отключения автозагрузки сервера Apache используется следующая команда:

Опция «-f» здесь используется для того, чтобы скрипт не запрашивал подтверждения выполнения команды.

Источник

Ubuntu, CentOS – Enable or Disable Service Autostart in Linux

Very often it is needed to enable or disable autostart of some services in Linux.

There are different init systems exist, but on Ubuntu and CentOS the most common are SysV , Upstart and systemd .

Depending on distribution, the behavior of a service during system’s boot in Linux can be configured with systemctl or chkconfig commands.

This tutorial shows how to enable or disable autostart of system services in the most popular Linux distributions – Ubuntu and CentOS.

Cool Tip: Want to become a DevOps engineer? Then you must know Git! This article helps to catch the Git basics really quickly! Read more →

Читайте также:  Если переустановить windows itunes

Ubuntu-18.04

Supported releases: Ubuntu-15.04, 15.10, 16.04, 16.10, 18.04.

It is now used by default in most Linux distributions and is fully supported in Ubuntu-15.04 and later releases.

It goes with systemctl command line tool, that among the other things, can enable and disable services at boot time.

Check if service is enabled or disabled on startup:

Disable service autostart on Ubuntu-18.04:

Enable service autostart on Ubuntu-18.04:

Ubuntu-14.04

Supported releases: Ubuntu-9.10, 10.04, 10.10, 11.04, 11.10, 12.04, 12.10, 13.04, 13.10, 14.04, 14.10.

Check if service is enabled or disabled on startup:

Disable service autostart on Ubuntu-14.04:

Enable service autostart on Ubuntu-14.04:

CentOS-7

In CentOS-7, it replaces Upstart as the default init system.

systemd goes with systemctl command line utility that is the central management tool for systemd , that among the other things, can enable and disable services at boot time.

Cool Tip: Learn how to disable SELinux temporary or permanently! Read more →

Check if service is enabled or disabled on startup:

Disable service autostart in CentOS-7:

Enable service autostart in CentOS-7:

CentOS-6

Cool Tip: Learn how to disable iptables on CentOS-6! Read more →

Check if service is enabled or disabled on startup:

Источник

Enabling and disabling services during start up in GNU/Linux

This guide shows you how to enable and disable services in Linux. This is the command line method of enabling and disabling services. Some Linux distributions like Fedora, Ubuntu and so on do provide a GUI front-end as well.

In any Linux distribution, some services are enabled to start at boot up by default.

On my machine, I have PCMCIA, Cron, Postfix Mail Transport Agent . just to name a few, which start during boot up.

You should run only those services that are absolutely necessary. Disable the rest, as they can be potential security risks and also waste hardware resources.

For example, my machine does not have any PCMCIA cards so I can safely disable it. Same is the case with Postfix which is also not used.

So how do you disable these services so that they are not started at boot time?

The answer to that depends on the type of Linux distribution you are using.

True, many Linux distributions including Ubuntu bundle with them a GUI front end to accomplish the task which makes it easier to enable and disable the system services.

But there is no standard GUI utility common across all Linux distributions. And this makes it worth while to learn how to enable and disable the services via the command line.

Most Linux distributions have one thing in common. That being, all the start-up scripts are stored in the /etc/init.d/ directory.

Update: As pointed out in the comments below, some Linux distributions such as Slackware use the BSD style of init scripts which are in /etc/rc.d

Lets say, you want to enable Apache web server in different run levels. Then you should have a script related to the Apache web server in the /etc/init.d/ directory.

The script is usually created at the time of installing the software. And in my machine (which runs Ubuntu), it is named apache2 . Where as in Red Hat, it is named httpd . Usually, the script will have the same name as the process or daemon.

Here I will explain different ways of enabling and disabling the system services.

How to enable and disable services in Red Hat

Red Hat, Fedora, and Red Hat based Linux distributions such as CentOS make use of the script called chkconfig to enable and disable the system services running in Linux.

How to enable a service

As an example, lets enable the Apache web server to start in run levels 2, 3, and 5. This is how it is done.

We first add the service using chkconfig script. Then turn on the service at the desired run levels.

This will enable the Apache web server to automatically start in the run levels 2, 3 and 5. You can check this by running the command —

How to disable a service

Red Hat/Fedora also have a useful script called service which can be used to start or stop any service. For example, to start Apache web server using the service script, the command is as follows —

and to stop the service.

The options being start , stop and restart which are self explanatory.

How to enable or disable services in Debian / Ubuntu

To Enable and disable services across runlevels in Debian, Ubuntu, and other Debian based Linux distributions we use a script called update-rc.d .

How to enable a service

As an example, to enable Apache web server in Debian, do the following —

Читайте также:  Как запустить регистрацию windows

. this will enable the Apache web server to start in the default run levels of 2,3,4 and 5. Of course, you can do it explicitly by giving the run levels instead of the defaults keyword as follows:

The above command modifies the sym-links in the respective /etc/rc X .d directories to start or stop the service in the destined runlevels. Here X stands for a value of 0 to 6 depending on the runlevel. One thing to note here is the dot ( . ) which is used to terminate the set which is important. Also 20 and 80 are the sequence codes which decides in what order of precedence the scripts in the /etc/init.d/ directory should be started or stopped.

To enable the service only in runlevel 5 , you do this instead —

How to disable a service

To disable the service in all the run levels, you execute the command:

Here -f option which stands for force is mandatory.

How to enable or disable services in Gentoo

Gentoo Linux also uses a script to enable or disable services during boot-up. The name of the script is rc-update . Gentoo has three default run levels. They are —

How to enable a service

Lets set Apache web server to start in the default runlevel.

How to disable a service

To remove the web server, use the del option as follows.

List all running services

To list all the running services at your run level and check their status , you use the rc-status command.

How to enable and disable services manually

I remember the first time I started using Linux, there were no such scripts to aid the user in enabling or disabling the services during start-up.

You did it the old fashioned way which was creating or deleting symbolic links in the respective /etc/rc X .d/ directories. Here X in rcX.d is a number which stands for the runlevel.

As an example, here is a listing of all the services started in runlevel 5 in my PC running Ubuntu.

And the output is .

As you can see, all the content in the /etc/rc5.d directory are symbolic links pointing to the corresponding script in the /etc/init.d directory.

There can be two kinds of symbolic links in the /etc/rcX.d/ directories.

One starts with the character ‘S’ followed by a number between 0 and 99 to denote the priority, followed by the name of the service you want to enable.

The second kind of symlink has a name which starts with a ‘K’ followed by a number and then the name of the service you want to disable.

So in any /etc/rcX.d directory, at any given time, for each service, there should be only one symlink of the ‘S’ OR ‘K’ variety but not both .

So coming back to our Apache example, suppose I want to enable Apache web server in the run level 5 but want to disable it in all other run levels, I do the following:

First to enable the service for run level 5, I move into /etc/rc 5 .d/ directory and create a symlink to the apache service script residing in the /etc/init.d/ directory as follows:

This creates a symbolic link in the /etc/rc5.d/ directory which the system interprets as — start ( S ) the apache service before all the services which have a priority number greater than 20 .

If you do a long listing of the directory /etc/rc5.d in your system, you can find a lot of symlinks similar to the one below.

Now if I start a service, I will want to stop the service while rebooting or while moving to single user mode and so on. So in those run levels I have to create the symlinks starting with character ‘ K ‘.

So going back to the apache2 service example, if I want to automatically stop the service when the system goes into run level 0, 1 or 6, I will have to create the symlinks in the /etc/rc0.d, /etc/rc1.d/, /etc/rc6.d/ directories as follows —

One interesting aspect here is the priority. Lower the number, the higher is the priority.

So since the starting priority of apache2 is 20 — that is apache starts way ahead of other services during startup, we give it a stopping priority of 80.

There is no hard and fast rule for this but usually, you follow the formula as follows:

If you have ‘N’ as the priority number for starting a service, you use the number (100-N) for the stopping priority number and vice versa.

Источник

How to Enable or Disable Services in Ubuntu Systemd/Upstart

Often, there is a need to enable or disable services temporarily or permanently on our Ubuntu system. Sometimes, we may require certain services to start up automatically on boot up e.g ssh or web servers and sometimes we may need to disable services we no longer require and are hogging the CPU and RAM.

Читайте также:  Меняем тему оформления windows

In this tutorial, we take a look at how we can enable and disable services on Ubuntu. To do this, we must first understand that there are 3 main init systems for Ubuntu

Each init system has a different way of starting and stopping services. We’ll take a look at each one of these.

How to enable and disable services in Systemd init

To start a service in systemd run the command as shown:

For example, to start apache web service, run

To verify that the service is running, run

Output

To stop the service running service

To confirm that the service is not running, run

Output

To enable apache2 service on boot up run

To disable apache2 service on boot up run

To restart the service

To check whether the service is currently configured to start on the next boot up

Output

To check whether the service is active

Output

How to remove Systemd services completely

What if you installed a package, and later on decide that you don’t need it anymore. How do you go about removing it completely? Follow the commands below.

First, stop the service

Then disable the service

Removing the service in systemd

How to enable and disable services in Upstart init

Upstart init system was unveiled just before systemd It was used in Ubuntu 9.10 to Ubuntu 14.10. It was later phased out paving way for systemd init in Ubuntu 15.04 and newer versions. In this example, let’s see how we can start and stop, enable and disable services in Ubuntu 14.04.

Upstart makes use of config files for controlling services. These files are held under the /etc/init directory. These files are made up of plain text sections organized in stanzas and each stanza describes a service and how it works.

To check whether a service is running or not run the command below

In this example, we’ll check the status of cups, a Linux print server.

Output

To stop the service run the command below

Output

To enable a service in Upstart init

In /etc/init/*.conf file, you’ll find the «respawn» directive which jump-starts a service should it crash unexpectedly or should the system reboot. Its normally enabled by default.

For example , in /etc/init/cups.conf file below,

the first argument (3) is the number of attempts it will try to restart and the second argument (12) is the time interval between retries. If it fails to restart automictically. it will be kept in a stopped state.

To disable a service in upstart init

run the command below

This creates an override file that disables a service without altering the job definition at all.
For cups service, the command will be

Upon a reboot of the system, cups will be in a stopped state. If you wish to re-enable the service, you must delete the /etc/init/cups.override file.

Sysv-rc-conf tool

This is a text-based console that gives you an overview of different service and runlevels they are scheduled to start. It can be installed using the following command

To execute the tool, run

Jobs-Admin tool

This is another feature that allows you to control services and processes in a GUI environment. You can install this by running.

How to enable and disable services in SysV init

To enable a service in SysV init run

For instance, If you want to enable apache web server, you would run

To disable a service , run

Nearly all Linux systems run on Systemd init From Ubuntu, Debian, RHEL, and CentOS. You’ll, therefore, discover that you’ll be using more of the systemctl command to start, stop, enable and disable services. We welcome you to try out the commands as shown in this article. Thank you.

Read Also:

8 Comments. add one

Sometimes it needs «systemctl mask foo.service» to stop service «foo» start on boot.

Thanks for the article.

On Ubuntu (admittedly an old one for many reasons), I just found the SysV command to disable a service wasn’t quite what was written:

# update-rc.d disable apache2
update-rc.d: /etc/init.d/disable: file does not exist

Instead, it’s «update-rc.d disable»:
# update-rc.d apache2 disable
update-rc.d: warning: apache2 start runlevel arguments (none) do not match LSB Default-Start values (2 3 4 5)
update-rc.d: warning: apache2 stop runlevel arguments (none) do not match LSB Default-Stop values (0 1 6)
Disabling system startup links for /etc/init.d/apache2 .
Removing any system startup links for /etc/init.d/apache2 .
/etc/rc0.d/K09apache2
/etc/rc1.d/K09apache2
/etc/rc2.d/S91apache2
/etc/rc3.d/S91apache2
/etc/rc4.d/S91apache2
/etc/rc5.d/S91apache2
/etc/rc6.d/K09apache2
Adding system startup for /etc/init.d/apache2 .
/etc/rc0.d/K09apache2 -> ../init.d/apache2
/etc/rc1.d/K09apache2 -> ../init.d/apache2
/etc/rc6.d/K09apache2 -> ../init.d/apache2
/etc/rc2.d/K09apache2 -> ../init.d/apache2
/etc/rc3.d/K09apache2 -> ../init.d/apache2
/etc/rc4.d/K09apache2 -> ../init.d/apache2
/etc/rc5.d/K09apache2 -> ../init.d/apache2

There is a typo: «systenctl» should be «systemctl» in the box near «To stop a service».

Источник

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