- Linux directory structure:/etc explained
- The history of /etc folder in Linux/Unix
- /etc folder content can be divided into following groups
- Table files (The ***TAB) in /etc folder in Linux
- Running Configuration files(rc) in /etc folder
- Config files in /etc folder
- Deny/Allow files in /etc folder
- Directories in /etc folder
- Ok that’s enough, How many folders and files I should learn like this?
- Other files in /etc folder
- Основные конфигурационные файлы Linux
- Конфигурационные файлы Linux
- 1. /etc/adjtime
- 2. /etc/bash.bashrc
- 3. /etc/crontab
- 4. /etc/environment
- 5. /etc/fstab
- 6. /etc/group
- 7. /etc/hostname
- 8. /etc/hosts
- 9. /etc/hosts.allow и /etc/hosts.deny
- 10. /etc/issue и /etc/issue.net
- 11. /etc/ld.so.conf
- 12. /etc/localtime
- 13. /etc/login.defs
- 14. /etc/mime.types
- 15. /etc/modprobe.d/
- 16. /etc/modules-load.d/
- 17. /etc/nsswitch.conf
- 18. /etc/ntp.conf
- 19. /etc/os-release
- 20. /etc/passwd
- 21. /etc/profile
- 22. /etc/resolv.conf
- 23. /etc/sddm.conf
- 24. /etc/shadow
- 25. /etc/sudoers
- 26. /etc/sysctl.conf
- 27. /etc/vconsole.conf
- 28. /boot/grub/grub.cfg
- Выводы
Linux directory structure:/etc explained
ETC is a folder which contain all your system configuration files in it. Then why the etc name?
“etc” is an English word which means etcetera i.e in layman words it is “and so on”. The naming convention of this folder is having some interesting history.
The history of /etc folder in Linux/Unix
In initial days of UNIX OS development there is a folder for each type of data like /bin folder for all your executable binaries
/boot folder for all booting related information.
/dev folder for all hardware devices attached to machine.
But people encountered a situation to keep some files which can be a config file or a data file or a socket file or some other files. So they implemented a folder to keep all these files in it and they named it as /etc(As said earlier etcetera). As time passed the meaning of this folder has changed but not the name “etc”. Now /etc folder means a central location for all your configuration files are located and this can be treated as nerve centre of your Linux/Unix machine.
Coming back to our /etc folder explanation, one post on this is not sufficient and the number files/folder in this directory will depend on the applications you install in it. Below are some list of files/folders commonly installed in most of Linux/Unix machines. I thought of posting this long time back almost three years back along with /bin, /boot, /dev but did not find a good way to approach this folder as number of files/folders are huge in number. Today I come up with a solution which I felt it’s bit easy for people who are new to Linux can understand without much fuss.
/etc folder content can be divided into following groups
Please note that this is a special post which I will modify continuously based on readers inputs.
Table files (The ***TAB) in /etc folder in Linux
These are the files which end with tab or start with tab(which is short form of table) such as crontab, fstab, inittab etc. These files main intention is to keep a table of content for their corresponding settings. Below are some of the files which fall under this category.
/etc/crontab –For doing scheduling
/etc/inittab –Contains what are the run-levels, what system have to do at each run-level and default run-level info.
/etc/fstab –Contains file system mounting information and we can edit this file to mount file system permanently and delete mount points.
/etc/mtab –Contains all mounted device status like what devices are mounted, where they mounted and properties of mount points.
/etc/quotatab –Quota related table for mentioning different qutos
/etc/rwtab –When your computer comes back up, the root and any other system partitions will be mounted read-only. All the files and directories listed in /etc/rwtab will be mounted read-write on a tmpfs file system. You can add additional files and directories to rwtab to make them writeable after reboot.
Some other table files are as below.
Running Configuration files(rc) in /etc folder
These are again a type of config files which will force a service to start/stop, for a user to use specific environment etc.
/etc/bash.bashrc –System wide bash shell running configuration file.
/etc/inputrc — Global inputrc for libreadline
/etc/nanorc –Nano editor running configurations
rc0.d, rc1.d, rc2.d, rc3.d, rc4.d, rc5.d, rc6.d, rcS.d –running configurations like what services has to start and stop for each run level from zero to six. If you observe rcS.d this folder is same as rc1.d folder which means Single run level.
/etc/rc.local –This file contains commands which need to be executed after completing booting. we can edit this file and keep the commands which we want to execute at the time of booting.
vimrc –VIEW Improved editor system level configuration is stored here.
wgetrc –wget related running configurations.
Other RC files:
Config files in /etc folder
These are the main configuration files for many applications installed in your machine. These files are text files which can be edited with editors like VI editor so that applications works according to your requirement.
/etc/asound.conf –Configuration file for your speakers and audio devices.
/etc/dnsmasq.conf –DNS client related configuration file
/etc/exports –NFS share configuration file. In this file we will share our local folder to a specific IP address or network with different.
/etc/grub.conf –Main configuration file for grub boot loader
/etc/shadow –User login password hashes are stored here.
/etc/group –User groups information such as which user belongs to which group, what is GID etc.
/etc/passwd –User configurations such as user login name, shell, UID and GID are stored here.
/etc/my.cnf –Mysql configuration file.
/etc/mdadm.conf –Raid configuration file.
/etc/hosts –Hosts to IP address mapping file, This is mother of all name to IP matching files.
/etc/resolv.conf –DNS and domain client configuration file. With out proper DNS server in this file, we can not access internet.
/etc/rsyslog.conf –Remote syslog server configuration file.
/etc/securetty –Root login control file.
/etc/sestatus.conf –SELinux configuration file.
Other configuration files are as below
Deny/Allow files in /etc folder
These are the files which contain what users are allowed/denied for particular service, what IP address are allowed/denied to access our services etc.
/etc/at.deny –Keep users in this file to deny at jobs execution.
/etc/at.allow –Keep users in this file to allow at jobs execution.
/etc/hosts.allow –TCP wrapper files for allowing services for a particular host/network.
/etc/hosts.deny –TCP wrapper files for allowing services for a particular host/network.
Directories in /etc folder
abrt/ -Useful for automatic bug reporting tool used by your vendor for reporting bugs.
acpi/ -The Advanced Configuration and Power Interface (ACPI) specification provides an open standard for device configuration and power management. This folder contain configuration files related to ACPI
alsa/ -The Advanced Linux Sound Architecture (ALSA) provides audio and MIDI functionality to the Linux operating system.
alternatives/ –A required folder/command to change default applications. Suppose you want to use emacs editor instead of vi editor then this folder contain those details.
cron.d/, cron.daily/, cron.deny, cron.hourly/, cron.monthly/, crontab, cron.weekly/ –Crontab related files and folders for effective management for scheduling in Linux.
default/ –Some of the common configuration files are located here.
Ok that’s enough, How many folders and files I should learn like this?
I want easiest and detailed way to learn this stuff. Is there any way to do that?
Yes, man pages will come for your rescue. Suppose you want to know more about passwd file then execute following command
aliases and aliases.db — Files which are related to Sendmail and postfix mail servers to mention alias
Other folders:
Other files in /etc folder
/etc/issue –This is the file which is displayed at every login session.
/etc/motd –Message of the day file which is shown after you login to any machine.
/etc/services –Available services and their corresponding port information is stored here
/etc/protocols –Available network protocols such as IGP, ISIS etc.
/etc/redhat-release –If yu find this file, that indicates you are working on Redhat based machines and it contain OS version and release details.
/etc/debian_version –If yu find this file, that indicates you are working on Debian based machines and it contain OS version and release details.
/etc/shells –All available/installed shells in your machine.
/etc/sudoers –Main sudo configuration file.
In our next post we will see /home directory.
Источник
Основные конфигурационные файлы Linux
Операционная система Linux в отличие от Windows не имеет общего реестра для хранения настроек системы, все настройки хранятся в конфигурационных файлах. Большинство этих файлов размещено в папке /etc/.
Настройки большинства системных и сторонних программ находятся в этих файлах, это могут быть настройки графического сервера, менеджера входа, системных служб, веб-сервера, системы инициализации.
Только часть файлов конфигурации находятся в других папках, например, файлы настройки рабочего окружения в домашнем каталоге пользователя. Новичкам очень важно понимать, за что отвечают те или иные конфигурационные файлы, чтобы при необходимости очень быстро сориентироваться. В этой статье мы рассмотрим основные конфигурационные файлы Linux, их расположение и предназначение.
Конфигурационные файлы Linux
На самом деле в самой системы Linux конфигурационных файлов нет. Поскольку операционная система — это всего лишь набор программ и ядро, то все эти файлы были созданы определенными программами и читаются ими же для настройки поведения. Большинство файлов, которые мы привыкли считать стандартными, относятся к системе инициализации или к другим системным утилитам.
Как я уже сказал, большинство файлов размещено в /etc. Название этой папки расшифровывается как «et cetera», что с латинского означает «и другие» или «и так далее». Сначала давайте посмотрим содержимое каталога /etc Linux:
Здесь достаточно много различных файлов. Дальше мы рассмотрим назначение многих из них. Список отсортирован по алфавиту.
1. /etc/adjtime
Этот конфигурационный файл отвечает за настройку формата системного времени и читается службой systemd-timedated. Время может быть представлено в двух вариантах: LOCAL — время текущего часового пояса и UTC — время по Гринвичу. Вы можете вручную менять значение или воспользоваться утилитой timedatectl.
2. /etc/bash.bashrc
Этот файл принадлежит командной оболочке bash. Это не совсем конфигурационный файл — а скрипт, его содержимое выполняется при запуске каждого экземпляра bash для настройки оболочки. Точно так же выполняется содержимое файла
/.bashrc для каждого пользователя.
3. /etc/crontab
Crontab — файл настройки планировщика cron. Здесь записываются все задания, которые должен выполнить планировщик, а также время и периодичность. Этот файл не принято редактировать напрямую. Для этого используется утилита crontab -e.
4. /etc/environment
Здесь содержатся переменные окружения, которые будут загружены для каждого сеанса терминала, независимо от того запущен он на локальной машине или по ssh. Файл читается скриптами Bash во время инициализации оболочки.
5. /etc/fstab
Наверное, все уже знают файл /etc/fstab. Здесь выполняется настройка монтирования файловых систем во время загрузки. В современных системах он читается systemd и все записи на ходу транслируются в юнит-файлы, с помощью которых уже выполняется монтирование. Смотрите также: автоматическое монтирование fstab.
6. /etc/group
В этом файле хранятся все группы пользователей, которые есть в системе. С помощью него вы можете посмотреть список групп, их идентификаторы или добавить новые. Но добавлять группы с помощью редактирования файла не принято, для этого есть утилита usermod.
7. /etc/hostname
В этом файле содержится имя хоста, файл будет прочитан во время загрузки системы и указанное имя компьютера установится в системе. Вы будете его видеть в приглашении ввода терминала или в информации о системе.
8. /etc/hosts
Файл /etc/hosts позволяет задавать псевдонимы для различных сетевых узлов. Таким образом, компьютер не обращается к DNS для получения IP домена, а берет его из hosts. Это позволяет, например, заблокировать доступ к нежелательным сайтам просто перенаправив их на localhost или же получить доступ к сайту по ip, которому еще не присвоен домен.
9. /etc/hosts.allow и /etc/hosts.deny
С помощью этих двоих файлов можно настраивать права доступа ко всем локальным службам. Например, вы можете разрешить доступ к службе apache только с локального компьютера. Это очень сильно повысит безопасность системы, если ваш компьютер подключен к публичной сети.
10. /etc/issue и /etc/issue.net
Баннер, который будет выводиться при входе в командную оболочку локально или по SSH. Обычно там выводится версия ядра и дистрибутива Linux, но вы можете заменить эту информацию по своему усмотрению.
11. /etc/ld.so.conf
В этом файле содержатся пути к папкам, в которых компоновщик linux ld.so будет искать динамические библиотеки во время запуска программ. Папки /lib64, /lib, /usr/lib64 и /usr/lib будут проверены автоматически.
12. /etc/localtime
Это символическая ссылка, которая указывает на файл часового пояса в папке /usr/share/zoneinfo/. Редактировать файл не нужно, а для изменения настроек нужно создать символическую ссылку на другую временную зону.
13. /etc/login.defs
Файл /etc/login.defs отвечает за настройку поведения утилиты управления пользователями и параметры входа в систему. Вы можете настроить какой минимальный и максимальный id нужно выдавать, что делать с папкой пользователя при удалении и многое другое, количество попыток входа и таймаут, а также многое другое.
14. /etc/mime.types
В этом файле содержатся общесистемные правила преобразования расширений файлов в понятные системе MIME типы данных. Затем уже система выбирает, чем открыть тот или иной тип данных.
15. /etc/modprobe.d/
Папка /etc/modprobe содержит конфигурационные файлы со списками модулей ядра, которые не нужно загружать при старте системы, псевдонимами для существующих модулей, а также позволяет задавать настройки для модулей.
16. /etc/modules-load.d/
Папка /etc/modules-load.d/ содержит файлы со списками модулей, которые должны быть загружены при запуске системы. Имя файла не важно, но он должен иметь расширение .conf.
17. /etc/nsswitch.conf
Этот файл задает настройки порядка разрешения имен в системе для всех программ, написанных на Си или С++. Например, нужно сначала просматривать локальную сеть и систему, или сразу же отправлять запрос к DNS.
18. /etc/ntp.conf
Файл ntp.conf отвечает за настройку службы синхронизации времени — ntpd. В файле указаны адреса ntp серверов, с которых служба будет получать время, а также общие настройки.
19. /etc/os-release
Отображает очень подробную информацию об установленном дистрибутиве:
20. /etc/passwd
Файл содержит список всех зарегистрированных в системе пользователей, а также дополнительные настройки для них, например, оболочку, дату смены пароля и дату отключения аккаунта, кроме самого пароля. Напрямую файл лучше не редактировать, а использовать утилиту для управления пользователями adduser или deluser.
21. /etc/profile
Файл /etc/profile, точно так же как и /etc/environment загружается и выполняется при запуске любой командной оболочки в системе. Но в отличие от environment, это скрипт, а значит, он может задавать не только переменные, но и выполнять различные команды для инициализации оболочки.
22. /etc/resolv.conf
В этом файле содержатся IP адреса DNS серверов, которые будет использовать компьютер. В большинстве дистрибутивов вы можете редактировать файл вручную или же использовать специальные утилиты.
23. /etc/sddm.conf
Это конфигурационный файл Linux для настройки менеджера входа sddm, для других менеджеров входа будут свои файлы настройки. Здесь можно изменить максимальный и минимальный ID пользователя, который может войти в систему, например, чтобы разрешить авторизацию root, изменить тему, добавить вход без пароля и многое другое.
24. /etc/shadow
Раньше пароли пользователя содержались в файле /etc/passwd, но поскольку к нему мог получить доступ любой пользователь, это было небезопасно, несмотря на то, что пароли зашифрованы. Поэтому все пароли были вынесены в /etc/shadow. Вы можете изменить пароль пользователя.
25. /etc/sudoers
/etc/sudoers — это файл настройки прав доступа к утилите sudo. Эта утилита позволяет выполнять команды от имени других пользователей, в том числе от имени суперпользователя. Но использовать ее могут только те пользователи, которые прописаны в этом файле.
26. /etc/sysctl.conf
Этот файл отвечает за настройку параметров ядра во время выполнения. Тут вы можете задать все параметры из подсистемы /sys/ и они будут сохранены после перезагрузки.
27. /etc/vconsole.conf
У этого файла только одна цель — задать кодировку, раскладку клавиатуры и шрифт по умолчанию для всех виртуальных консолей, запускаемых на машине.
28. /boot/grub/grub.cfg
Этот конфигурационный файл Linux находится не в /etc из-за своего особого предназначения. Здесь содержатся все настройки загрузчика, пункты меню и другие параметры, поэтому он должен быть доступен еще до того как была подключена корневая файловая система.
Выводы
В этой статье мы рассмотрели основные конфигурационные файлы Linux, которые находятся в папке /etc/. Возможно, какие-либо важные файлы, по вашему мнению, упущены, тогда обязательно расскажите о них и их предназначении в комментариях!
Источник