Версия сервиса в linux

10+ commands to list all systemctl services with status

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

# chkconfig postfix on Note: Forwarding request to 'systemctl enable postfix.service'. Created symlink /etc/systemd/system/multi-user.target.wants/postfix.service → /usr/lib/systemd/system/postfix.service.

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 :

# service sshd restart Redirecting to /bin/systemctl restart sshd.service

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

# cat /etc/redhat-release Red Hat Enterprise Linux release 8.1 (Ootpa)

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.

With systemd we have unit files which are further classified into service , socket , target etc. So you must be very clear on your requirement if you wish to list only services, or sockets or any other type of unit.

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:

10+ commands to list all systemctl services with status

List all the unit files

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

10+ commands to list all systemctl services with status

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

Читайте также:  Linux sudo user list

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:

10+ commands to list all systemctl services with status

Here this command will show all the installed unit files independent of their state unlike list-units which shows only the active unit files. Adding —all with this command will have no advantage.

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-unit-files --type=service

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-units --all --type=mount

systemctl list mount paths

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

List state of services

To check if a service is enabled/disabled/static/indirect, you must use list-unit-files with systemctl while to check if a service is running/active/failed/dead etc then you must use systemctl list-units . To get complete list of supported options with list-units and —state , use systemctl —state=help

systemctl list enabled services

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

# systemctl list-unit-files --type=service --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-unit-files --type=service --state=enabled,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-units --type=service --state=running

systemctl list running services

systemctl list failed services

To list failed services you can use —state=failed

# systemctl list-units --type=service --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.

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:

# systemctl show sshd --property=SubState SubState=running

To check if a service is active or inactive :

# systemctl show sshd --property=ActiveState ActiveState=active
# systemctl is-active sshd active

To check if a service is loaded or not:

# systemctl show sshd --property=LoadState LoadState=loaded

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

Читайте также:  Linux microsoft system window

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.

Buy GoLinuxCloud a Coffee

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

Thank You for your support!!

Источник

Полезные команды для управления Apache в Linux

img

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

 Apache HTTPD

Убедитесь, что следующие команды должны выполняться от имени пользователя root или sudo и работать с любым дистрибутивом Linux, таким как CentOS, RHEL, Fedora, Debian и Ubuntu.

Про Linux за 5 минут

  • Установка Apache Server

    $ sudo apt install apache2 [On Debian/Ubuntu] $ sudo yum install httpd [On RHEL/CentOS] $ sudo dnf install httpd [On Fedora 22+] $ sudo zypper install apache2 [On openSUSE]

    Проверка версии Apache

    Чтобы проверить установленную версию вашего веб-сервера Apache в вашей системе Linux, выполните следующую команду.

    Server version: Apache/2.4.6 (CentOS) Server built: May 5 2019 01:47:09

    Если вы хотите увидеть номер версии Apache и параметры компиляции, используйте флаг -V, как показано ниже.

    Server version: Apache/2.4.6 (CentOS) Server built: May 5 2019 01:47:09 Server's Module Magic Number: 20120211:24 Server loaded: APR 1.4.8, APR-UTIL 1.5.2 Compiled using: APR 1.4.8, APR-UTIL 1.5.2 Architecture: 64-bit Server MPM: prefork threaded: no forked: yes (variable process count) Server compiled with. -D APR_HAS_SENDFILE -D APR_HAS_MMAP -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled) -D APR_USE_SYSVSEM_SERIALIZE -D APR_USE_PTHREAD_SERIALIZE -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT -D APR_HAS_OTHER_CHILD -D AP_HAVE_RELIABLE_PIPED_LOGS -D DYNAMIC_MODULE_LIMIT=256 -D HTTPD_ROOT="/etc/httpd" -D SUEXEC_BIN="/usr/sbin/suexec" -D DEFAULT_PIDLOG="/run/httpd/httpd.pid" -D DEFAULT_SCOREBOARD="logs/apache_runtime_status" -D DEFAULT_ERRORLOG="logs/error_log" -D AP_TYPES_CONFIG_FILE="conf/mime.types" -D SERVER_CONFIG_FILE="conf/httpd.conf"
    Проверка на ошибки синтаксиса конфигурации Apache

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

    AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using merionet.ru. Set the 'ServerName' directive globally to suppress this message Syntax OK
    Запуск сервиса Apache
    ------------ On CentOS/RHEL ------------ $ sudo systemctl start httpd [On Systemd] $ sudo service httpd start [On SysVInit] ------------ On Ubunt/Debian ------------ $ sudo systemctl start apache2 [On Systemd] $ sudo service apache2 start [On SysVInit]
    Включение службы Apache

    Предыдущая команда пока только запускает службу Apache, чтобы включить автозапуск при загрузке системы, выполните следующую команду.

    ------------ On CentOS/RHEL ------------ $ sudo systemctl enable httpd [On Systemd] $ sudo chkconfig httpd on [On SysVInit] ------------ On Ubunt/Debian ------------ $ sudo systemctl enable apache2 [On Systemd] $ sudo chkconfig apache2 on [On SysVInit]
    Перезапуск службы Apache
    ------------ On CentOS/RHEL ------------ $ sudo systemctl restart httpd [On Systemd] $ sudo service httpd restart [On SysVInit] ------------ On Ubunt/Debian ------------ $ sudo systemctl restart apache2 [On Systemd] $ sudo service apache2 restart [On SysVInit]
    Просмотр состояния сервиса Apache

    Чтобы проверить информацию о состоянии времени выполнения службы Apache, выполните следующую команду.

    ------------ On CentOS/RHEL ------------ $ sudo systemctl status httpd [On Systemd] $ sudo service httpd status [On SysVInit] ------------ On Ubunt/Debian ------------ $ sudo systemctl status apache2 [On Systemd] $ sudo service apache2 status [On SysVInit]
    Перезагрузка сервиса Apache

    Если вы внесли какие-либо изменения в конфигурацию сервера Apache, вы можете указать службе перезагрузить свою конфигурацию, выполнив следующую команду.

    ------------ On CentOS/RHEL ------------ $ sudo systemctl reload httpd [On Systemd] $ sudo service httpd reload [On SysVInit] ------------ On Ubunt/Debian ------------ $ sudo systemctl reload apache2 [On Systemd] $ sudo service apache2 reload [On SysVInit]
    Остановка службы Apache
    ------------ On CentOS/RHEL ------------ $ sudo systemctl stop httpd [On Systemd] $ sudo service httpd stop [On SysVInit] ------------ On Ubunt/Debian ------------ $ sudo systemctl stop apache2 [On Systemd] $ sudo service apache2 stop [On SysVInit]
    Показать справку Apache Command

    И последнее, но не менее важное: вы можете получить справку о служебных командах Apache в systemd, выполнив следующую команду.

    Usage: httpd [-D name] [-d directory] [-f file] [-C "directive"] [-c "directive"] [-k start|restart|graceful|graceful-stop|stop] [-v] [-V] [-h] [-l] [-L] [-t] [-T] [-S] [-X] Options: -D name : define a name for use in directives -d directory : specify an alternate initial ServerRoot -f file : specify an alternate ServerConfigFile -C "directive" : process directive before reading config files -c "directive" : process directive after reading config files -e level : show startup errors of level (see LogLevel) -E file : log startup errors to file -v : show version number -V : show compile settings -h : list available command line options (this page) -l : list compiled in modules -L : list available configuration directives -t -D DUMP_VHOSTS : show parsed vhost settings -t -D DUMP_RUN_CFG : show parsed run settings -S : a synonym for -t -D DUMP_VHOSTS -D DUMP_RUN_CFG -t -D DUMP_MODULES : show all loaded modules -M : a synonym for -t -D DUMP_MODULES -t : run syntax check for config files -T : start without DocumentRoot(s) check -X : debug mode (only one worker, do not detach)

    На этом пока все! В этой статье мы объяснили наиболее часто используемые команды управления службами Apache / HTTPD, которые полезно будет знать, включая запуск, включение, перезапуск и остановку Apache.

    Читайте также:  Alt linux server samba

    Источник

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