February 16, 2023

Linux. Собеседование

Linux. Собеседование

Что такое LA? В каких единицах измеряется?

LA (load average) - параметр, определяющий среднюю нагрузку на систему за период времени (1 мин, 5 минут, 15 минут). Изменяется в количестве задач на одно ядро процессора. На нагрузку системы также влияет количество задач ввода-вывода и задержка сети. Также влияние на расчета LA оказывает:

  • Технология Hyper-Threading, которая делит одно физическое ядро на 2 логических,
  • Технология Turbo Bust, которая позволяет разгонять тактовую частоту процессора и работать на частоте выше заявленной, т.е. выше номинальной частоты (время на обработку одной задачи уменьшается).

Что будет если на сервере LA = 200?
Вероятно, что на сервере будет наблюдаться замедленная работа сервисов, но если параметр LA равен количеству ядер в системе или количеству потоков в системе, то данная нагрузка является нормальной.

Почему при высоких показателях значения LA на сервере может не наблюдаться проблем (консоль ssh отзывается, сервисы работают в обычном режиме)?

На параметр нагрузки LA влияет также и ожидание ввода-вывода (параметр wa в утилите top) в дисков и задержка сети. Данные параметры могут не влиять на работу основных сервисов в системе, но учитываются при расчете общей нагрузки на систему.

uptime - load average

We can get the load average from commands like top or uptime.

If load > # of CPUs, it may mean CPU saturation.

$ uptime
 16:48:25 up 32 min,  2 users,  load average: 0.58, 1.13, 2.46

From left to right, these numbers show us the average load over the last 1 minute, the last 5 minutes, and the last 15 minutes. In other words, the above output indicates:

load average over the last 1 minute: 0.58
load average over the last 5 minutes: 1.13
load average over the last 15 minutes: 2.46

Assuming 1 cpu machine, it means:

load average over the last 1 minute: 0.58 => The CPU idled for 42% of the time
load average over the last 5 minutes: 1.13 => .13 processes were waiting for the CPU
load average over the last 15 minutes: 2.46 => On average, 1.46 processes were waiting for the CPU

Actually, if the machine has 2 CPUs, then it would mean:

load average over the last 1 minute: 0.58 => The CPU idled for 142% of the time
load average over the last 5 minutes: 1.13 => .87 processes were waiting for the CPU
load average over the last 15 minutes: 2.46 => On average, 0.46 processes were waiting for the CPU

Что такое системный вызов, какие они бывают?

Системный вызов - обращение программы к ядру операционной системы для выполнения какой-либо операции.

В Unix, Unix-like и других POSIX-совместимых операционных системах популярными системными вызовами являются:
- open,
- read,
- write,
- close,
- wait,
- exec,
- fork,
- exit,
- kill.

Что такое сигнал в Unix, зачем они нужны и разница между 9 и 15 сигналами?

Сигнал - в Unix-like операционных системах - асинхронное (в случайное время) уведомление процесса для обработки какого-либо события. Один из основных способов взаимодействия между процессами.

Посылка сигналов от одного процесса к другому обычно осуществляется при помощи системного вызова *kill*. Его первый параметр – PID процесса, которому посылается сигнал; второй параметр – номер сигнала.
kill(1111, SIGTERM);

Стандарт POSIX определяет 28 сигналов. Некоторые из них:

| Сигнал | Код | Описание |

| SIGTERM | 15 | Сигнал завершения (сигнал по умолчанию для утилиты kill) |
| SIGKILL | 9 | Безусловное завершение |
| SIGSTOP | 23 | Остановка выполнения процесса |
| SIGHUP | 1 | Закрытие терминала (перечитать конфигурацию) |
| SIGINT | 2 | Сигнал прерывания (Ctrl-C) с терминала |

Что такое inode? Какая информация там хранится?

Inode (индексный дескриптор) - структура данных, в которой хранятся метаданные файла и перечислены блоки с данными файла. Хранит всю информацию, кроме имени файла и данных. Каждый файл в данном каталоге является записью с именем файла и номером индекса. Вся остальная информация о файле извлекается из таблицы индексов путем ссылки на номер индекса. Номера inodes уникальны на уровне раздела. Каждый раздел как собственная таблица индексов. Если у вас закончились inode, вы не можете создавать новые файлы, даже если у вас есть свободное место на данном разделе.

Inodes хранит метаданные о файле, к которому он относится. Эти метаданные содержат всю информацию об указанном файле.
- Размер.
- Разрешение.
- Владелец/группа.
- Расположение жесткого диска.
- Дата/время.
- Любая другая необходимая информация.

Что такое hard link? В чем разница между hard link и soft link? Примеры их практического применения.

Hard link:
Ссылка на файл в файловой системе с использованием такого же inode идентификатора, как у файла, на который ссылаемся.
Создадим файл *realFile*.

touch realFile

Создадим hard link командой `ln <целевой_файл> <файл_ссылка>`:

ln realFile hardLink

Проверим, что inode у файла *realFile* и hard ссылке *hardLink* имеют одинаковый идентификатор.

$ ls -li
итого 0
2359720 -rw-r--r-- 2 rmntrvn rmntrvn 0 апр 25 23:24 hardLink
2359720 -rw-r--r-- 2 rmntrvn rmntrvn 0 апр 25 23:24 realFile

Как видно realFile и hardLink имеют одинаковый идентификатор inode.

Soft link:
Создадим soft ссылку на файл *realFile*.

ln -s realFile softLink

Проверим, что чистовой идентификатор *softLink* отличается от числового идентификатора *realFile*.

$ ls -li
итого 0
2359720 -rw-r--r— 2 rmntrvn rmntrvn 0 апр 25 23:24 hardLink
2359720 -rw-r--r— 2 rmntrvn rmntrvn 0 апр 25 23:24 realFile
2366763 lrwxrwxrwx 1 rmntrvn rmntrvn 8 апр 25 23:29 softLink -> realFile

Некоторые нюансы:
- Soft ссылки используют различные номера inode, чем основные файлы.
- Soft ссылки становятся полезными, если исходный файл был удален.
- Soft ссылки могут быть созданы из каталогов.
- Soft ссылка может быть создана на пересечении файловых систем.

- Hard ссылка может размещаться только на том же логическом разделе, что и оригинальный файл. Это связано с независимой идентификацией файлов на разных разделах.
- Создание жестких ссылок не поддерживается для папок — только для файлов.
- Файловая система должна поддерживать работу с hard ссылками.

What are an Inode and PID?

An inode is a file structure that stores metadata for files in Linux. The metadata includes file size, permissions needed to access the file, user and group ID, creation timestamp, and the path to the file.

An inode number is a unique number or integer given to each file on a Linux system.

$ ls -li ravi.txt 

1594567 -rwxrwxr-x 1 tecmint tecmint 0 Oct 28 10:58 ravi.txt

1594567 is the inode number and the -i flag shows the inode of the ravi.txt file.

A PID (Process ID) is a unique ID given to each running process on a Linux system. We can use the pidof command to find the process ID of any running program.

$ pidof firefox

40982

Какие состояния процессов существуют? Что значит состояние процесса D?

| **Статус** | **Описание** |
|:----------------------------------------------:|:---------------------------------------:|
| R (running or runnable) | Выполняется или готов к выполнению |
| D (uninterruptible sleep) | Ожидает записи на диск |
| S (interruptible sleep) | Неактивен (< 20 s) |
| T (stopped by job control signal) | Остановлен или трассируется отладчиком |
| Z (zombie) | зомби |
| W (paging (not valid since the 2.6.xx kernel)) | Процесс выгружен на диск |
| < | Процесс имеет повышенный приоритет nice |
| N | Процесс имеет пониженный приоритет nice |
| L (locked) | Некоторые страницы блокированы в ядре |
| s | Процесс является лидеров сеанса |

Linux Process is a type of process that can be in a number of different states. The process enters these states from start till end. Process states in Linux are as follows:

  • New/Ready: In this state, a new process is created and is ready to run.
  • Running: In this state, the process is being executed.
  • Blocked/Wait: In this state, the process is waiting for input from the user and if doesn't have resources to run such as memory, file locks, input, then it can remain in a waiting or blocked state.
  • Terminated/Completed: In this state, the process has completed the execution or terminated by the OS.
  • Zombie: In this state, the process is terminated but information regarding the process still exists and is available in the process table

Что такое процесс-зомби и процесс-сирота? Можно ли самостоятельно сделать зомби?

Зомби-процесс, также называемый в Linux несуществующим или мертвым процессом, представляет собой процесс, который завершил выполнение, но его запись остается в таблице процессов. Обычно это происходит из-за отсутствия соответствия между родительским и дочерним процессами. Этот процесс происходит для дочернего процесса, поскольку родительскому процессу необходимо прочитать состояние дочернего процесса. После завершения с помощью системного вызова wait этот процесс удаляется из таблицы процессов.

Процесс-зомби - дочерний процесс в Unix-системе, завершивший своё выполнение, но ещё присутствующий в списке процессов операционной системы, чтобы дать родительскому процессу считать код завершения.

Удаление зомби возлагается на родительский процесс или системный вызов `wait()` также может это выполнить, поэтому перед ее вызовом не нужно проверять, продолжает ли выполняться требуемый дочерний процесс. Если родительский процесс не удалит своих потомков, то они останутся в состоянии зомби.

Убить зомби-процесс невозможно. Чтобы убить зомби-процесс нужно найти родительский процесс и завершить его или перезапустить. Найти зомби-процессы и их родителей можно следующей командой:

ps ajx | grep -w Z

PID'ы процессов родителей в 3 колонке. Убить процесс следующей командой:

kill -9 <PID процесса родителя>

Процесс-сирота — в семействе операционных систем UNIX вспомогательный процесс, чей основной процесс (или связь с ним) был завершен нештатно (не подав сигнала на завершение работы).

Отличие в том, что процесс-сирота (orphan process) всё еще активен. Его родительский процесс был по какой-либо причине прерван, и сирота теперь переходит под руководство init, чей ID процесса равен 1. PPID orphan процесса получит значение 1. Пользователь также может создать подобный процесс, отсоединив его от терминала. Сиротские процессы используют много ресурсов, их легко найти с помощью top или htop.

В отличии от процесса-сироты, зомби-процесс неактивен, но контролируется родительским процессом, пока тот не решит, что статус выхода дочерних процессов больше не нужен. Он не использует ресурсы и не может быть запланирован для выполнения. Иногда родительский процесс удерживает дочерний процесс в состоянии зомби, чтобы гарантировать, что будущие дочерние процессы не получат тот же PID. Если вы уничтожите родителя зомби-процесса, зомби-процесс тоже умрет. Для этого найдите родительский PID (PPID) зомби и отправьте ему сигнал SIGCHLD (17): kill -17 ppid.

Что такое файловый дескриптор? Какая информация там хранится?

Файловый дескриптор - неотрицательное целое число, которое используется в интерфейсе между пространством пользователя и пространством ядра (kernel) для идентификации ресурсов файла / сокета. Когда создаётся новый поток ввода-вывода, ядро возвращает процессу, создавшему поток ввода-вывода, его файловый дескриптор.

Что такое buffer/cache память? Для чего нужна?

buff/cache память - рассчитанная память, которая зарезервирована, но может быть освобождена при необходимости и используется для быстрого доступа программами к данным, которые находятся в оперативной памяти (быстрой памяти).

buffers — буферы в памяти — страницы памяти, зарезервированные системой для выделения их процессам, когда они затребуют этого, так же известна как heap-memory;
cached — файлы, которые недавно были использованы системой/процессами и хранящиеся в памяти на случай если вскоре они снова потребуются.

Представлен вывод команды `free`.

$ free -m
total used free shared buff/cache available
Mem: 6930 3598 843 183 2489 2919
Swap: 15999 4 15995

Почему доступной (available) памяти сейчас 2919, если свободной (free) памяти 843?

- Total. Эта цифра представляет всю существующую память.
- Used вычисление общего значения оперативной памяти системы за вычетом выделенной свободной, разделяемой, буферной и кэш-памяти.

used = total - free - buff/cache

- Free – свободная память в системе.
- Shared – память, используемая (преимущественно) в tmpfs
- Buffer, и Cache идентифицируют память, используемую для нужд ядра / операционной системы. Буфер и кеш складываются вместе, а сумма указывается в разделе «buff/cache».
- Available – примерное количество оперативной памяти, доступное для запуска новых приложений без использования ими раздела подкачки. В отличие от поля free, это поле принимает в расчёт страницу cache и также то, что не вся рекуперируемая (пригодная для повторного использования) память будет возвращена для рекуперации из-за того, что элементы используются в данный момент.

Порядок загрузки дистрибутива Linux.

1. Включение компьютера кнопкой.
2. Загрузить BIOS / UEFI из NVRAM.
3. Собрать сведения об аппаратуре.
4. Выбрать устройства для запуска (диск, сеть).
5. Идентифицировать системный раздел EFI.
6. Загрузить BIOS / UEFI из NVRAM.
7. Определить какое ядро загрузить.
8. Загрузить ядро.
9. Создать структуры данных ядра.
10. Запустить init / systemd как PID 1.
11. Выполнить сценарии запуска.
12. Запустить систему.

What’s Run level 0?
The run level 0 denotes system halt. It means the system can be powered off without any activity.

What do you mean by a run level?
In Unix-based OSes, a Run level signifies the state of the computer after boot. Runlevel is previously set on various Linux distributions. There are seven Run levels, starting from zero to six. Run levels determine the programs to be executed after the operating system boots up. System admins assign a default run level as per their requirements. You can find out your computer’s current run level using the /sbin/runlevel command.

What is the name and path of the main system log?

By default, the main system log is '/var/log/messages'. This file contains all the messages and the script written by the user. By default all scripts are saved in this file. This is the standard system log file, which contains messages from all system software, non-kernel boot issues, and messages that go to 'dmesg'. dmesg is a system file that is written upon system boot.

What are the different layers of Linux?

Answer:

Below are the different layers of Linux as following:

  • Hardware’s – Innermost layer consists of physical devices like RAM, CPU, etc. There might be driver software to communicate with devices in some OS.
  • Kernel – Kernel is a heart of an OS with hides the complexities of the underlying hardware and provides a high-level abstraction to upper layers. There are different types of kernels like a microkernel, Monolithic Kernel, etc. Linux kernel is a Monolithic type.
  • Shell – Shell is a program running on top of the Kernel, which acts as a primary method of interaction between user and kernel. Simply saying it is a program that can run other programs. Nowadays GUI replaces shell to a large extent. Shell accepts commands and passes them for execution.
  • Utility Programs(Utilities) – These programs or software running on a top layer of OS help users with day-to-day generic activities like schedule a cron job or a specific task like create text documents.

What are file permissions in Linux? Name different types of file systems in Linux.

There are three owners in the Linux System i.e., user, group, and others. These owners have three types of permissions defined as listed below:

  • Read (r): It allows the user to open and read the file or list the directory.
  • Write (w): It allows the user to open and modify the file. One can also add new files to the directory.
  • Execute (x): It allows the user to execute or run the file. One can also lookup a specific file within a directory.

What is a “/proc” file system?

Proc file system is a pseudo or virtual file system that provides an interface to the kernel data structure. It generally includes useful information about processes that are running currently. It can also be used to change some kernel parameters at runtime or during execution. It is also regarded as a control and information center for the kernel. All files under this directory are named virtual files.

Как в Linux найти, кто использует файл?

Lsof используется файловой системой, чтобы определить, кто использует какие-либо файлы в этой файловой системе. Вы можете запустить команду lsof в файловой системе Linux, и выходные данные идентифицируют владельца и информацию о процессах, использующих файл, как показано в следующем листинге выходных данных.

Список всех открытых в Linux файлов

$ lsof /dev/null
COMMAND    PID    USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
systemd   1480 tecmint    0r   CHR    1,3      0t0    6 /dev/null
sh        1501 tecmint    0r   CHR    1,3      0t0    6 /dev/null

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

Список файлов, открытых конкретным пользователем (при использовании в вашей системе замените tecmint действительным именем пользователя)

$ lsof -u tecmint
COMMAND    PID    USER   FD      TYPE             DEVICE  SIZE/OFF       NODE NAME
systemd   1480 tecmint  cwd       DIR                8,3      4096          2 /
systemd   1480 tecmint  rtd       DIR                8,3      4096          2 /
systemd   1480 tecmint  txt       REG                8,3   1595792    3147496 /lib/systemd/systemd

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

Определение процесса, прослушивающего порт

$ sudo lsof -i TCP:80
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
httpd    903   root    4u  IPv6  20222      0t0  TCP *:http (LISTEN)
httpd   1320 apache    4u  IPv6  20222      0t0  TCP *:http (LISTEN)

https://github.com/mxssl/sre-interview-prep-guide/blob/master/README.md

https://www.brendangregg.com/USEmethod/use-linux.html

https://www.bogotobogo.com/DevOps/DevOps-Sys-Admin-Interview-Questions-Linux-Monitoring-System-Application-Performance-Tuning-Tools.php

Explain ulimit VS umask.

ulimit is a Linux built-in command that offers excellent control over available resources to shell or start processes. If needed, the user can choose to limit to a specific range by customizing the limits.conf file. They could also update system settings in the sysctl.conf file.

Talking about umask, it refers to using a file creation mask. umask determines the permissions of a file or directory when the user creates one.

What is SELinux?

(One of the Red Hat Linux interview questions that you’ll most likely be asked).

SELinux is Security-Enhanced Linux. As the name suggests, it’s a Linux program with enhanced security features. It protects the server from compromised daemons and misconfigurations. In addition, SELinux is used to access control implementation for the Linux kernel.

It also sets limits and instructs server programs to access specific permitted files and security policies, defining the action to be taken.

Представлен вывод команды top. Что означает каждая запись в выводе?

   top - 21:29:24 up 14:18,  1 user,  load average: 0,78, 1,48,   1,10
   Tasks: 277 total,   3 running, 274 sleeping,   0 stopped,      0 zombie
   %Cpu(s): 12,4 us,  2,5 sy,  0,1 ni, 84,8 id,  0,1 wa,  0,0   hi,  0,1 si,  0,0 st
   KiB Mem :  7106404 total,   306972 free,  3127144 used,    3672288 buff/cache
   KiB Swap:  8191996 total,  8191996 free,        0 used.    3270520 avail Mem 

top - название утилиты.

21:29:24 - текущее время системы.

up 14:18 - сколько часов:минут система работает с момента последнего запуска.

1 user - количество пользователей авторизованных в системе.

load average: 0,78, 1,48, 1,10 - параметр средней нагрузки на систему за период времени 1 минута, 5 минут, 15 минут.

277 total - всего процессов в системе.

3 running - количество процессов в работе.

274 sleeping - количество процессов в состоянии sleeping: ожидает какого-либо события или сигнала.

0 stopped - количество приостановленных процессов сигналом STOP или выполнением трассировки.

0 zombie - количество зомби-процессов, которые завершили своё выполнение, но присутствующие в системе, чтобы дать родительскому процессу считать свой код завершения.

Параметр
us (user) - Использование процессора пользовательским процессами
sy (system) - Использование процессора системным процессами
ni (nice) - Использование процессора процессами с измененным приоритетом с помощью команды nice
id (idle) - Простой процессора. Можно сказать, что это свободные ресурсы
wa (IO-wait) - Говорит о простое, связанным с вводом/выводом
hi (hardware interrupts) - Показывает сколько процессорного времени было потрачено на обслуживание аппаратного прерывания
si (software interrupts) - Показывает сколько процессорного времени было потрачено на обслуживание софтверного прерывания
st (stolen by the hypervisor) - Показывает сколько процессорного времени было «украдено» гипервизором

KiB Mem - количество оперативной памяти в кибибайтах (кратно 1024):
7106404 total -- всего доступно оперативной памяти в системе,
306972 free -- свободно оперативной памяти для использования,
3127144 used -- использовано оперативной памяти,
3672288 buff/cache -- буферизовано/закешировано оперативной памяти.

KiB Swap - количество swap-памяти в кибибайтах (кратно 1024), которые выделено на диске:
8191996 total - всего выделено swap-памяти,
8191996 free - свободно swap-памяти
0 used - использовано swap-памяти,
3270520 avail Mem - доступно для использования swap-памяти.

Как в утилите top в Linux посмотреть нагрузку на каждое ядро процессора?

В утилите top нажать `1`, чтобы отобразить все ядра в системе.

Как в утилите top в Linux посмотреть какой командой был запущен процесс?

В утилите top нажать `c`, чтобы отобразить команды, которыми были запущены процессы.

Где хранятся имена файлов/директорий?

- Inodes не содержат имён файлов, только другие метаданные файла.
- Каталоги Unix представляют собой списки ассоциативных структур, каждая из которых содержит одно имя файла и один номер индекса.
- Драйвер файловой системы должен найти каталог, ищущий определенное имя файла, а затем преобразовать имя файла в правильный соответствующий номер индекса.

Таким образом имя файла/директории хранится в информационной структуре директорий.

Как удалить файл с именем `-rf`?

rm ./-rf

Как посмотреть описание дискриптора? Как посмотреть время последней модификации файла?

Посмотреть полную информацию по дискриптору возможно командой stat <path_to_file>.
Время модификации:
stat --format=%y dira

Для чего нужна переменная окружения PATH?

Переменная окружения PATH содержит абсолютные пути директорий, в которых производится поиск исполняемых файлов при вводе команд

Как посмотреть нагрузку на диски?

Установить утилиту `sysstat`, проверить нагрузку на диски `iostat -xtc`.

Что такое файл в понятиях Unix-like операционных системах?

Файлы - это объекты, в которые мы записываем информацию и наши данные, исполняемые файлы, но кроме этих привычных нам понятий здесь есть файлы специального назначения - файлы устройств, файлы туннелей, сокетов и многое другое.

Типы файлов в Linux:
- Обычные файлы, для хранения информации;
- Специальные файлы - для устройств и туннелей;
- Директории.

Что такое RAID? Какие массивы бывают?

RAID (Redundant Array of Independent Disks) - избыточный массив независимых дисков, технология виртуализации данных для объединения нескольких физических дисковых устройств в логический модуль для повышения отказоустойчивости и производительности.

В зависимости от количества дисков и класса отказоустойчивости существуют следующие основные типы RAID:
RAID 0:
RAID 1:
RAID 5:
RAID 6:
RAID 10:

При каком количестве одновременно вышедших из строя дисков обеспечивает работоспособность RAID 6?

2 диска.

В чем разница между объявлением переменной `export VAR="VALUE"` и `VAR="VALUE"` в bash?

При объявлении переменной через export - переменная будет доступна в любых других процессах, при обычном объявлении переменной - переменная будет доступна только в запущенном процессе.

Как остановить выполнение скрипта в bash при возникновении ошибки в команде?

Команда set -e завершит скрипт с ошибкой, в случае, если в нижеследующем bash коде будет обнаружена ошибка. По-умолчанию bash скрипт продолжает работу, если в ходе выполнения возникла ошибка.

Что в bash скрипте означает команда `set -euo pipefail`?

Команда set устанавливает аттрибуты оболочки с опеределенных опций.
Опция -e - означает, что скрипт будет остановлен, когда произойдет ошибка в ходе его выполнения.
Опция -u - означает, что скрипт будет остановлен, если в ходе скрипта, будет обнаружена переменная, которая не определена.
Опция -o pipefail - означает, что скрипт будет остановлен, если в ходе пайплайна команд будет выявлена ошибка.

Как активировать debug режим в bash?

Команда set -x в начале скрипта активирует вывод в консоль debug информации.

Что значит $@ в bash?

$@ - все параметры переданные скрипту.

Какой код сигнала будет выполнен при исполнении команды kill <PID>?

Сигнал SIGTERM (код 15) - это сигнал по-умолчанию отправляемый при вызове команды kill. Это указывает процессу на завершение работы и обычно считается сигналом для использования при чистом завершении работы.

Как выполнить фильтрацию вывода команды, чтобы на экран были выведены только ошибки (STDERR), игнорируя STDOUT?

cmd 2>&1 >/dev/null | grep pattern

Какую команду необходимо выполнить, чтобы посмотреть какие пользователи вошли в систему в систему?

Команда w покажет список пользователей, которые вошли на сервер.

Какой файл необходимо отредактировать, чтобы отключить ssh аутентификацию по паролю?

Необходимо редактировать файл /etc/ssh/sshd_config, отвечающий за конфигурацию сервиса ssh.

В каком файле находится информация о смонтированных каталогах в файловую систсему?

Файл /etc/fstab содержит информацию о смонтированных каталогах в файловую систему.

Что выведет команда cat a и почему?

mkdir /tmp/abc
cd /tmp/abc
ls >a 2>b
cat a

`cat a` выведет
a
b

Обработка команды идёт справа налево. Сначала создается файл *b*, потом создается файл *a*, команда `ls` отображает список файлов в текущей директории (файлы *a* и *b* уже созданы) в одну колонну и перенаправляет стандартный поток вывода (`>`) в файл *a*, а стандартный поток ошибок `2` в файл *b*.

В bash-скрипте указан аттрибут оболочки `set -x`. В одной из команд происходит ошибка и скрипт завершает свою работу. Как сделать, чтобы при возникновении ошибки в определенной команде скрипт продолжил свою работу?

1 вариант: указать || true после выполнения команды с ошибкой.
<command with error> || true

2 вариант: до выполнения данной команды указать `set +e` для игнорирования ошибок, начиная со следующей строки и после выполнения команды указать `set -e` для завершения работы скрипта в случае ошибки, начиная со следующей строки.
sh
set -e
<command 1>
<command 2>
set +e
<command 3 wih error>
set -e

Why is the tar command used?

The tar command is used for extracting or creating an archived file. If you wish to extract all of the files from the sample.tar.gz package, use the following command:

$ tar -xvzf sample.tar.gz


How to find logs older than seven days and remove them?

find /path/ -type f -mtime +7 -name ‘*.gz’ -execdir rm — ‘{}’ \;

Details:

find: the UNIX command for finding files/directories/links etc.

/path/: the directory path where you are searching for old logs

-type f: specifying to check only for files.

-name ‘*.gz’: will find for the files that end with “.gz”.

-mtime +7: only consider the ones with modification time older than 7 days.

-execdir … \;: for each such result found, execute the following command.

rm — ‘{}’: remove the file; the {} part is where the output from previous command will be given as input.

  1. What is cron job and how to set it?

cron is a kind of a daemon that executes scripts or programs at specific time intervals.

These commands are called cron jobs.

This is like a scheduler for system admins and developers. Many use cases are present for which we can set cron jobs like log rotation,

emailing users to trigger any update for automatic data backup at any specified timings.

find the standard cron job writing style:-

* * * * * script1

please find the details below for all the description for every *:-

# +—————- minute (0 – 59)

# | +————- hour (0 – 23)

# | | +———- day of month (1 – 31)

# | | | +——- month (1 – 12)

# | | | | +—- day of week (0 – 6) (Sunday=0)

# | | | | |

* * * * * command to be executed

if you want to save the output of the cron job, you can execute the below command.

Timing Execute Path to script Output

* * * * * /usr/bin/scripts /var/www/html/crontest/cron.sh > /dev/null 2>&1

  1. How to copy the files in Linux?

cp command

we can use cp command to copy any data from the current directory to a different directory.

For example:-the command cp test.txt /home/users/files would create a copy of test.txt at “/home/users/files”

  1. How to move the files in Linux?

mv command

mv command can be used to move files from one folder to another; This is also used to rename the files.

This works as cp command only. We need to type mv, the file’s name, and the destination’s directory.

For example: mv file.txt /home/users/Docs.

  1. What is sudo command?

sudo stands for “SuperUser Do”, this command enables you to perform tasks that require administrative or root permissions.

However, it is not recommended to use sudo command because most of the tasks would be performed as a particular user.

  1. Which command is used to check disk space and disk usage?

df command

df command is used to check the disk space, shown in percentage and KBs.

If you want to see the report in megabytes, type df -m.

du command

this is used to check Disk Usage.

However, the disk usage summary will show disk block numbers instead of the usual size format.

If you want to see it in bytes, kilobytes, and megabytes, add the -h argument to the command line.

  1. How to check first few and last few lines of any linux file?

The head command is used to view the first lines of any text file. By default, it will show the first ten lines,

but you can change this number to your liking.

For example, if you only want to show the first five lines.

head -n 5 filename.ext.

tail command

This one has a similar function to the head command, but instead of showing the first lines,

the tail command will display the last ten lines of a text file.

tail -n filename.ext.

10. How to check the difference between two Linux files?

diff command

the diff command compares the contents of two files line by line.

After analyzing the files, it will output the lines that do not match.

Programmers often use this command when they need to make program alterations instead of rewriting the entire source code.The simplest form of this command

diff file1.ext file2.ext

Which command is used to execute a shell file?

First Set execute permission on your script using chmod command:

chmod +x script-name-here.sh

To run your script:

./script-name-here.sh

Another option to execute shell script:

sh script-name-here.sh

What is interactive and non-interactive shell?

Interactive Shell

/bin/bash and /bin/sh 

Non-interactive shell

/sbin/nologin 

What is the absolute and relative path?

Absolute path is the full path of the directory. It always starts with “/” .

Example:

cd  /var/tmp/abrt/

Relative path is necessary from current location to reach particular directory doesn’t start with “/”.

Example:

cd .. ,   cd –

How will you pass and access arguments to a script in Linux?

For pass arguments in script “scriptname arg1 arg2 arg3 …”

For access arguments in script can be accessed inside the script as “$1 , $2 .. $n”

https://www.mygreatlearning.com/blog/shell-scripting-interview-questions/

How to create multiple text files and directories?

To create multiple text file touch file name {} command is used.

Example:

Suppose we want create 4 files then we type:

#touch filename{1..4}

To create multiple directory mkdir filename {} command is used.

Example:

Suppose we want to create 4 directory, then we type:

mkdir filename {1..4}

What are file permissions in Linux? Name different types of file systems in Linux.

There are three owners in the Linux System i.e., user, group, and others. These owners have three types of permissions defined as listed below:

  • Read (r): It allows the user to open and read the file or list the directory.
  • Write (w): It allows the user to open and modify the file. One can also add new files to the directory.
  • Execute (x): It allows the user to execute or run the file. One can also lookup a specific file within a directory.

What is LVM and why is it required?

LVM (Logical Volume Management) is basically a tool that provides logical volume management for the Linux kernel. It is being introduced simply to make physical storage device management easier. It also includes allocating disks, striping, mirroring, resizing logical volumes. Its main advantages are increased abstraction, flexibility, and control. It simply allows for flexible disk space management. It is especially required to resize the size of the file system online. In Linux, the size of the LVM partition can be extended using “lvextend” command and can be reduced using “lvreduce” commands, respectively.

What do you mean by the daemons?

Daemons also referred to as the background process, is a long-running Linux program that runs in the background. They do not have any controlling terminal, therefore, they run in the background. These are the processes that are generally started when the system is bootstrapped and terminate or end only when the system is shut down. It is simply the way of extending the functionality of the base OS. It provides and offers several functions that are not available in OS. Its main purpose is to handle periodic requests and then forward the requests to the appropriate programs for execution

Name the first process that is started by the kernel in Linux and what is its process id?

The first process started by the kernel in Linux is “init” and its process id is 1

Linux. Networking

26. Why /etc/resolv.conf and /etc/hosts files are used?

/etc/resolv.conf: It is used to configure DNS name servers as it contains the details of the nameserver i.e., details of your DNS server. The DNS server is then used to resolve the hostname of the IP address.

/etc/hosts: It is used to map or translate any hostname or domain name to its relevant IP address.

27. What are the advantages of using NIC teaming?

NIC (Network Interface Card) teaming has several advantages as given below:

  • Load Balancing
  • Failover
  • Increases uptime

28. What do you mean by Network bonding?

Network Bonding, also known as NIC Teaming, is a type of bonding that is used to connect multiple network interfaces into a single interface. It usually improves performance and redundancy simply by increasing network throughput and bandwidth.

29. What are different network bonding modes used in Linux?

Different network bonding modes used in Linux are listed below:

  • Mode-0 (balance-rr): It is the default mode and is based on round-robin policy. It offers features like fault tolerance and load balancing.
  • Mode-1 (active-backup): It is based on an active-backup policy. In this, only one node responds or works at the time of failure of other nodes.
  • Mode-2 (balance-xor): It sets an XOR (exclusive-or) mode for providing load balancing and fault tolerance.
  • Mode-3 (broadcast): It is based on broadcast policy. It sets a broadcast mode for providing fault tolerance and can be used only for specific purposes.
  • Mode-4 (802.3ad): It is based on IEEE 802.3ad standard also known as Dynamic Link Aggregation mode. It sets an IEEE 802.3ad dynamic link aggregation mode and creates aggregation groups that share the same speed and duplex settings.
  • Mode-5 (balance-tlb): It is also known as Adaptive TLB (Transmit Load Balancing). It sets TLB mode for fault tolerance and load balancing. In this mode, traffic will be loaded based on each slave of the network.
  • Mode-6 (balance-alb): It is also known as Adaptive Load Balancing. It sets ALB mode for fault tolerance and load balancing. It doesn’t need any special switch support.

Name default ports used for DNS, SMTP, FTP, SSH, DHCP and squid.

Default ports used for various services are as follows:

Name three standard streams in Linux.

Standard streams are basically I/O (Input and Output) communication channels between a program and its environment in Linux. Input and output in the Linux environment are distributed across three standard streams. Three standard streams in Linux are as follows:

  1. Standard Input (stdin)
  2. Standard Output (stdout)
  3. Standard Error (stderr)

Linux Commands

34. What is netstat command?

netstat (Network statics) command is generally a networking tool being used for troubleshooting and configuration and used to display all network connections on a system. It simply provides a way to check whether various aspects of TCP/IP are working and what connections are present.

35. What is the ping command?

Linux ping (Packet Internet Groper) command is a command that is used to check connection status between source and destination. In simple words, this command is used to check whether a network is available and if the host is reachable. It can also be used to troubleshoot different connectivity issues, verify connectivity at an IP -level to a second TCP/IP device, and name resolution. One can use this command to test both the computer name and IP address of the computer.

36. Which command is used to check the default run level?

The command used to check the default run level is “/etc/inittab”.

37. Which command is used to check the size of file or directory?

The command used to check the size of the file or directory is “du”. Here “du” stands for disk usage that is used to check information of disk usage of files and directories on a machine. It is also used to display files and directory sizes in a recursive manner.

Example:
$ du -sh /var/log/*
1.8M /var/log/anaconda
384K /var/log/audit
4.0K /var/log/boot.log
0 /var/log/chrony
4.0K /var/log/cron
4.0K /var/log/maillog
64K /var/log/messages

38. Which command is used to count the number of characters in a file?

The command that is used to count the number of characters in a file in Linux is “wc”. Here “wc” stands for word count. It is used to count the number of lines, words, and characters in a text file.

39. What is the function of grep command?

Grep (Global regular expression print) is a command that is used to the global search for a string of characters in a specified file. The text search pattern is generally known as a regular expression. It simply makes use of pattern-based searching.

Syntax: grep [options] pattern [files]
Example: $ grep -c "linux" interview.txt

The above command will usually print the total count of the word “Linux” in the file “interview.txt”.

40. Explain working of env command.

“env” command is basically a shell command that is used to print a list of current environmental variables. Here, “env” stands for the environment. It can also run another process in another environment without any modification of the current environment. It allows you to run programs in a modified environment. It is generally used by shell scripts to launch the correct interpreter. It can also be useful for checking if wrong environment variables prevent the application from starting during troubleshooting.

Example:

$env
PHYTHON_PIP_VERSION=9.0L1
HOME=/root
DB_NAME=test
PATH=/usr/local/bin:/usr/local/sbin
LAND=C.UTF=8
PYTHON_VERSION=3.4.6
PWD=/
DB_URI=mongodb://database:27017/test

41. What is the pwd command?

“pwd” command is basically a command that is used to print the complete path of the current working directory starting from the root (/). Here, “pwd” stands for Print Working Directory. It is considered one of the most basic and most used commands in Linux. This command is usually a built-in shell command and is also available in different shells such as bash, ksh, zsh, bourne shell, etc.

42. Name the command that is used to check all the listening ports and services of your machine.

# netstat -ntlp

43. Which command is used to check the memory status?

The command used mostly to check memory status in Linux is “free”. Other commands that can be used are given below:

  • “cat” command: It can be used to show or display Linux memory information. (cat/proc/meminfo)
  • “vmstat” command: It can be used to report statistics of virtual memory.
  • “top” command: It can be used to check the usage of memory.
  • “htop” command: It can be used to find the memory load of each process.

44. What is pipe?

In Linux, a pipe is basically a form of redirection that is used to send the output of one command to another command for further processing. It simply takes the output from one command and uses it as an input for another. It provides asynchronous execution of commands with help of buffered I/O routines.

45. What are Linux directory commands?

There are basically five Linux directory commands that are used to work with files and directories as given below:

  • pwd: It stands for “print working directory”. This command is generally used to display the path of the present or current working directory.
    Syntax: $ pwd
  • cd: It stands for “change directory”. This command is generally used to change the present working directory to the directory that we want to work on.
    Syntax: $ cd <path to new directory>
  • Is: It stands for “list”. This command is generally used to show the full list of content of files and directories in the present working directory.
    Syntax: $ ls
  • mkdir: It stands for “make directory”. This command generally allows users to create directories in Linux.
    Syntax: $ mkdir <name (and path if required) of new directory>
  • rmdir: It stands for “remove directory”. This command is used to remove/delete each directory that is specified on the command line.
    Syntax: $ rmdir <name (and path if required) of directory>

46. What do you mean by unmask?

Umask, also known as user file-creation mask, is a Linux command that allows you to set up default permissions for new files and folders that you create. In Linux OS, umask command is used to set default file and folder permission. It is also used by other commands in Linux like mkdir, tee, touch, etc. that create files and directories.

Syntax: umask [-p] [-S] [mask]

Where,
[mask]: It represents the permission masks that you are applying.
[-S]: It displays the current mask as a symbolic value.
[-p]: It displays the current mask along with umask command thus allowing it to be copied and pasted as a future input.

47. Name the command used to review boot messages.

The command that is used to review boot messages is the “dmesg” command.

How to Run Multiple Commands in Single Command?

To run multiple commands one after the other in a single command, you can use either the semi-colon ';', double ampersand '&&', or '||' symbols.

  • X Y – This runs commands X and Y regardless of the success of X.
  • X && Y – This runs Y if and only if X runs successfully.
  • X || Y – This runs Y if and only if X failed.
Run Multiple Linux Commands

What is the Grep Command?

Grep is a command line tool for searching and matching text files or lines in a text file. It takes options and parameters which are used to manipulate or enhance the search output.

It takes the following syntax:

$ grep [options] pattern [files]

The following command counts the number of occurrences of the string ‘Unix‘ in file1.txt.

$ grep -c "Unix" file1.txt

How do Change the Permissions of a File or Directory?

The chmod command is the command that modifies the permissions of a file or directory.

It follows the syntax shown.

# chmod [OPTIONS] [permissions] file

For example. To assign octal permissions 755 (all permissions to the owner and read and write permissions only for the group members and everyone else) to a file called file1.txt, run the command.

# chmod 755 file1.txt

What are Hidden Files in Linux?

Hidden files are files that are preceded by a dot or period. They mostly contain configuration files that hold important data or settings. To view hidden files, use the ls command with the -la option.

$ ls -la
List Hidden Files in Linux

What is an Alias?

As the name suggests, aliases are like custom shortcuts used to represent a command (or set of commands) executed with or without custom options.

$ alias
List Linux Aliases

What are the Different Vim Modes?

The vim editor provides the following main modes:

  • Normal mode / Command mode – This is the default mode when you open a new file or an existing one. In this mode, you can run commands such as undo, redo, and paste.
  • Insert mode – This mode allows you to type in the text.
  • Visual mode – This mode lets you select text so that you can perform other tasks with it such as cop, cut or paste.

What is the Redirection Operator?

Redirection is the process of sending the output of the first command to another file. In addition, it’s also used to direct an output as an input to another process.

In Linux, redirection is achieved using either the ">" (greater-than symbol) or the "|" (pipe) operator which sends the standard output of one command to another command as standard input.

What command would you use for editing, searching, and replacing text in Linux?

Answer:

Editing:

You can use the cd command followed by the name of the text editor, like vi, with which you need to edit the file.

Searching:

You can search a file in Linux by using the command:

find –iname “filename”

For searching and printing text in a file in Linux, you can use the command grep.

Replacing:

This procedure involves using the Stream Editor (sed). You need to use the command:

sed -i 's/old-text/new-text/g' input.txt

Enter the text that needs to be replaced in place of the old-text and the new text that needs to be added in place of the new-text.

How to reduce or shrink the size of the LVM partition?

Follow these steps:
unmount the file system for reducing.
Check the file system after unmount.
Reduce the file system.
Reduce the Logical Volume size than Current size.
Recheck the file system for error.
Remount the file-system back to stage.

What are the uses of head and tail commands?

Answer: The head command is used for printing the first n lines of a file onto the terminal:

head 7 test.txt

By default (i.e., when you don’t specify a number), ten lines are printed.

The tail command prints the last n lines of a file. By default, n is ten unless specified. We can specify more than one file, in which case the output is displayed along with the file name.

tail 15 test.txt

Linux.Networking

How to check and verify the status of the bond interface?

To check if bonding is enabled, check if the /etc/modprobe. conf has the bonding module loaded in it and then see if the ifcfg-bondZ, ifcfg-ethX and ifcfg-ethY etc. have the correct entries. To check if the bonding is working fine, check /var/log/messages. If you ever wanted to check the status of a bonded interface configure in Linux (esp RHEL), you can check the status by running the following command [root@serverxyz bin]# cat /proc/net/bonding/bond0. i.e. assuming the name of your bond interface is bond0.

What are the different modes of Network Bonding in Linux?

Linux network Bonding is a creation of a single bonded interface by combining 2 or more Ethernet interfaces. This helps in high availability of your network interface and offers performance improvements on your data traffic flow. Bonding is also referred as nic trunking or teaming.
Different modes of bonding:
Mode 0 (balance-rr) This mode transmits packets in a sequential order from the first available slave through the last
Mode 1 (active-backup)
Mode 2 (balance-xor)
Mode 3 (broadcast)
Mode 4 (802.3ad)
Mode 5 (balance-tlb)
Mode 6 (balance-alb)

What will the following command do: $ grep “[^aeiou]” myfile

Answer: The command will match all lines that do not contain a vowel from the file ‘myfile’.

Do you know how to make changes to a large file without opening it?

Answer: For this, the sed command is used. For example, we want to replace the word ‘John’ with ‘Sam’. We can give the command as:

sed ‘s/John/Sam’ myfile.txt

44. What is the fork() system call? How is it different from vfork()?

Answer: The fork() call creates a child process from an existing (parent) process. In the process, the kernel places a copy of the parent process’s address space into the child process. vfork() call is faster as it does not do the above.

45. Can you explain the page fault and kinds of page faults?.

Answer: It is a situation when a process tries to refer to a page. But the page is not there in the main memory. The two types are validity fault (whether the page is valid or not) and protection fault (whether it can be accessed).

Differentiate between the absolute and relative path.

Answer: The absolute path is the complete path of a file or directory starting from its root directory. For example, /users/local/system

A relative path is the path from the current user directory and is not the complete path. It is the present working directory (PWD).

Linux.Security

Please explain the checking for Rootkit infections in Linux.

Answer: A Rootkit is an advanced form of malware that can yield a range of security issues and in many cases go undetected by average antivirus programs. Hence, advanced anti-spyware tools need to be used for checking Rootkit infections in Linux. One such is the rkhunter.

Rkhunter can be installed from the software repository by following the instructions of your distribution’s package management. Debian and Ubuntu users can use the (sudo) apt-get install rkhunter command while Red Hat-based distributions can use either the dnf or yum command.

A few other notable security tools available for checking rootkit infections in Linux are:

  • Chkrootkit
  • ClamAV
  • LMD (Linux Malware Detect)
  • Lynis

How will you setup Password Aging in Linux?

Answer: The chage command allows the system administrators in Linux to enforce password aging. The command is used to change the number of days between mandatory password resets. The /etc/login.defs file is responsible for handling system-wide configuration. It can be edited for:

  • PASS_MAX_DAYS – Defines the maximum number of days a password may be used.
  • PASS_MIN_DAYS – Defines the minimum number of days allowed between password changes.
  • PASS_WARN_AGE – Defines the number of days warning is given before a password expires.

How does Ctrl+Alt+Del key combination work in LINUX?

Answer: The Ctrl+Alt+Del key combination works in LINUX, just like it works in Windows. This key combination helps in restarting the system. However, in LINUX, there is no confirmation message displayed earlier to the restart, and the reboot occurs immediately.

How does Ctrl+Alt+F1(F2) key combination work in LINUX?

How can you enhance the security of the password file in Linux?

Linux keeps user account information in a text file called /etc/passwd. This file also store one way encrypted password. This file is accessed by several tools to get user information, so file need to world-readable. This is a security risk. To minimize the security risk you can use shadow password format. This method save account information in regular file /etc/passwd. However, the password is stored as a single "x" character (not actually stored in this file). A second file, called "/etc/shadow", contains encrypted password as well as other information such as account or password expiration values, etc. ...

Which account is created on Linux installation?

- With the installation of Linux, a super user account is created called as ‘root’.

Which daemon tracks events on your system?

- The syslogd daemon tracks the system information and saves it to specified log files.

Which command would you use if you want to remove the password assigned to a group?

- gpasswd – r removes the password from the group.
- Here, the gpasswd changes the password of the group and when it is accompanied by –r, the password gets removed.

You wish to print a file ‘draft’ with 60 lines to a page. What command would you use?

- The command that I would use is: pr -l60 draft
- The default page length when using pr is 66 lines.
- The -l option specifies a different length.

Which file would you examine to determine the levels of messages written to system log files?

- kernel.h

You are logged on as a regular user. Without logging off and logging on as root, you are required to create a new user account immediately. How would you do it?

- This can be achieved by issuing the su command.
- This will prompt you for the password of the root account.
- Providing the password, logs you in as root. Now, you can perform any administrative duties.

You are required to restore the file memo.ben. It was backed up in the tar file MyBackup.tar. Which command would you use to do it?

- The command that we would use is: tar xf MyBackup.tar memo.ben
- It uses the x switch to extract a file.

What is partial backup?

- When you select only a portion of your file hierarchy or a single partition to back up, it is called partial backup.

What is the fastest way to enter a series of commands from the command-line?

- Write the commands, each separated by a semi-colon. Press enter after the last command.
- The semi-colon would inform the shell that multiple commands are being entered at the command line, to be executed serially.

Which command is used to check the number of files and disk space used and the each user’s defined quota?

repquota command is used to check the status of the user’s quota along with the disk space and number of files used.

This command gives a summary of the user’s quota that how much space and files are left for the user. Every user has a defined quota in Linux. This is done mainly for the security, as some users have only limited access to files. This provides a security to the files from unwanted access. The quota can be given to a single user or to a group of users.

How secured is Linux? Explain.

Security is the most important aspect of an operating system. Due to its unique authentication module, Linux is considered as more secured than other operating systems. Linux consists of PAM. PAM is Pluggable Authentication Modules. It provides a layer between applications and actual authentication mechanism. It is a library of loadable modules which are called by the application for authentication. It also allows the administrator to control when a user can log in. All PAM applications are configured in the directory "/etc/pam.d" or in a file "/etc/pam.conf". PAM is controlled using the configuration file or the configuration directory.

Can Linux computer be made a router so that several machines may share a single Internet connection? How?

Yes a Linux machine can be made a router. This is called "IP Masquerade." IP Masquerade is a networking function in Linux similar to the one-to-many (1: Many) NAT (Network Address Translation) servers found in many commercial firewalls and network routers. The IP Masquerade feature allows other "internal" computers connected to this Linux box (via PPP, Ethernet, etc.) to also reach the Internet as well. Linux IP Masquerading allows this functionality even if the internal computers do not have IP addresses.
The IP masquerading can be done by the following steps:

1. The Linux PC must have an internet connection and a connection to LAN. Typically, the Linux PC has two network interfaces-an Ethernet card for the LAN and a dial-up PPP connection to the Internet (through an ISP).

2. All other systems on your LAN use the Linux PC as the default gateway for TCP/IP networking. Use the same ISP-provided DNS addresses on all systems.

3. Enable IP forwarding in the kernel. By default the IP forwarding is not enabled. To ensure that IP forwarding is enabled when you reboot your system, place this command in the /etc/rc.d/rc.local file.

4. Run /sbin/iptables-the IP packet filter administration program-to set up the rules that enable the Linux PC to masquerade for your LAN.

What is the minimum number of partitions that you need to install Linux?

Minimum 2 partitions are needed for installing Linux. The one is "/ or root" which contains all the files and the other is swap. Linux file system is function specific which means that files and folders are organized according to their functionality. For example, all executables are in one folder, all devices in another, all libraries in another and so on. "/ or root" is the base of this file system. All the other folders are under this one. "/" can be consider as "C:". Swap is a partition that will be used as virtual memory. If there is no more available RAM a Linux computer will use an area of the hard disk, called swap, to temporarily store data. In other words it is a way of expanding your computers RAM.

Which command is used to review boot messages?

dmesg command is used to review boot messages. This command will display system messages contained in the kernel ring buffer. We can use this command immediately after booting to see boot messages. A ring buffer is a buffer of fixed size for which any new data added to it overwrites the oldest data in it.

Its basic syntax is:dmesg [options]

Invoking dmesg without any of its options causes it to write all the kernel messages to standard output. This usually produces far too many lines to fit into the display screen all at once and thus only the final messages are visible. However, the output can be redirected to the less command through the use of a pipe, thereby allowing the startup messages to be viewed on one screen at a time
dmesg | less

Which utility is used to make automate rotation of a log?

logrotate command is used to make automate rotation of log.

Syntax of the command is:logrotate [-dv] [-f|] [-s|] config_file+

It allows automatic rotation, compression, removal, and mailing of log files. This command is mainly used for rotating and compressing log files. This job is done every day when a log file becomes too large. This command can also be run by giving on command line. We can done force rotation by giving –f option with this command in command line. This command is also used for mailing. We can give –m option for mailing with this command. This option takes two arguments one is subject and other is recipient name.

Which commands are used to set a processor-intensive job to use less CPU time?

nice command is used for changing priority of the jobs.

Syntax:nice [OPTION] [COMMAND [ARG]...]

Range of priority goes from -20 (highest priority) to 19 (lowest). Priority is given to a job so that the most important job is executed first by the kernel and then the other least important jobs. This takes less CPU times as the jobs are scheduled and are given priorities so the CPU executes fast. The priority is given by numbers like -20 describe the highest priority and 19 describe the least priority.

Which daemon is responsible for tracking events on Linux system?

syslogd is responsible for tracking system information and save it to the desired log files. It provides two system utilities which provide system logging and kernel message trapping. Internet and UNIX domain sockets support enable this utility package to support both local and remote logging. Every logged message contains at least a time and a hostname field, normally a program name field, too. So to track these information this daemon is used.

syslogd mainly reacts to the set of signals given by the user.

These are the signals given to syslogd:

- SIGHUP: This lets syslogd perform a re-initialization. All open files are closed, the configuration file (default is /etc/syslog.conf) will be reread and the syslog facility is started again.

- SIGTERM: The syslogd will die.

- SIGINT, SIGQUIT: If debugging is enabled these are ignored, otherwise syslogd will die.

- SIGUSR1: Switch debugging on/off. This option can only be used if syslogd is started with the - d debug option.

- SIGCHLD: Wait for Childs if some were born, because of waiting messages.

What is the minimum number of partitions that you need to install Linux?
Answer:
Minimum 2 partitions are needed for installing Linux

3. Is there any relation between modprobe.conf file and network devices?
Answer:
Yes, this file assigns a kernel module to each network device.
For Example:-
[root@localhost ~]# cat /etc/modprobe.conf
alias eth0 b44
Here, b44 is the kernel module for network device eth0.
We can confirm whether this module “b44” is present or not by the following command
[root@localhost ~]# lsmod |grep b44
b44 29005 0

How do you limit memory usage for commands?
Answer:
ulimit -Sv 1000 # 1000 KBs = 1 MB
ulimit -Sv unlimited # Remove limit

What is du -s * | sort -k1,1rn | head command used for?
Answer:
This command shows top disk users in current dir.

41. How to exit from vi editors?
Answer:
The following commands are used to exit from vi editors.
:wq saves the current work and exits the VI.
:q! exits the VI without saving current work.

42. How to delete information from a file in vi?
Answer:
The following commands are used to delete information from vi editors.
x deletes a current character.
dd deletes the current line.

strace

The strace is the tool that helps in debugging issues by tracing system calls executed by a program.

Here are the samples of strace command:

# Slow the target command and print details for each syscall:
strace command

# Slow the target PID and print details for each syscall:
strace -p PID

# Slow the target PID and any newly created child process, printing syscall details:
strace -fp PID

# Slow the target PID and record syscalls, printing a summary:
strace -cp PID

# Slow the target PID and trace open() syscalls only:
strace -eopen -p PID

# Slow the target PID and trace open() and stat() syscalls only:
strace -eopen,stat -p PID

# Slow the target PID and trace connect() and accept() syscalls only:
strace -econnect,accept -p PID

# Slow the target command and see what other programs it launches (slow them too!):
strace -qfeexecve command

# Slow the target PID and print time-since-epoch with (distorted) microsecond resolution:
strace -ttt -p PID

# Slow the target PID and print syscall durations with (distorted) microsecond resolution:
strace -T -p PID

The strace command allows us to trace the system calls made by a program. This is useful for debugging, or simply to find out what a program is doing. By default, strace writes its output to stderr, but we can change this using the -o filename option - from The Linux Programming Interface.

$ strace date
execve("/bin/date", ["date"], [/* 118 vars */]) = 0
brk(0)                                  = 0x18b5000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f809a459000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=154081, ...}) = 0
...
close(1)                                = 0
munmap(0x7f809a458000, 4096)            = 0
close(2)                                = 0
exit_group(0)                           = ?
+++ exited with 0 +++

Each system call is displayed in the form of a function call, with both input and out- put arguments shown in parentheses.

After the closing parenthesis of the traced call, strace prints an equal sign ( = ), fol- lowed by the return value of the system call. If the system call failed, the symbolic errno value is also displayed. Thus, we see ENOENT displayed for the failure of the access() call above.

Even for a simple program, the output produced by strace is made voluminous by the system calls executed by the C run-time startup code and the loading of shared libraries. For a complex program, the strace output can be extremely long.

For these reasons, it is sometimes useful to selectively filter the output of strace.

$ strace date 2>&1 | grep open
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
open("/etc/localtime", O_RDONLY|O_CLOEXEC) = 3

Another method is to use the -e option to select the events to be traced. For example, we can use the following command to trace open() and close() system calls:

$ strace -e trace=open,close date
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
close(3)                                = 0
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
close(3)                                = 0
open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
close(3)                                = 0
open("/etc/localtime", O_RDONLY|O_CLOEXEC) = 3
close(3)                                = 0
Sun Nov 29 14:40:08 PST 2015
close(1)                                = 0
close(2)                                = 0
+++ exited with 0 +++

dmesg

The dmesg command displays all messages from the kernel ring buffer which is a data structure that records messages related to the operation of the kernel. A ring buffer is a special kind of buffer that is always a constant size, removing the oldest messages when new messages come in.

We can use dmesg command to check why a process was killed. That happens if the process was consuming too much memory, and the kernel "Out of Memory" (OOM) killer will automatically kill the offending process.

$ dmesg | less
[   54.125380] Out of memory: Kill process 8320 (stress-ng-brk) score 324 or sacrifice child
[   54.125382] Killed process 8320 (stress-ng-brk) total-vm:1309660kB, anon-rss:1287796kB, file-rss:76kB
[   54.522906] gmain invoked oom-killer: gfp_mask=0x24201ca, order=0, oom_score_adj=0
[   54.522908] gmain cpuset=accounts-daemon.service mems_allowed=0
...

Дебаг

  • Инструмент dmesg
  • Демон syslog
  • Инструмент journald
  • Утилита strace
  • Утилита tcpdump

https://www.nightwolf.in/nightwolf-cotribution/linux_L3/

https://www.nightwolf.in/nightwolf-cotribution/linux_L2/

https://www.nightwolf.in/nightwolf-cotribution/linux_L1/

https://opensource.com/article/17/2/linux-boot-and-startup

https://awstip.com/sre-devops-interview-questions-linux-troubleshooting-1b8ffe82c16

https://www.golinuxhub.com/2018/06/scenario-based-interview-question-beginner-experience-linux/