Продолжаем рассматривать малоизвестные команды linux, которые могут быть очень полезными в повседеневной работе как на десктопе, так и на сервере.
12. Команда <space>
Все команды, которые вы вводите в терминале, записываются в истории, и затем могут быть запрошены с помощью команды history. Но есть ли способ обмануть команду history? Да, вы можете сделать это, и очень просто. Просто вставьте один или несколько пробелов перед вводом команды в терминале, и она не будет записана.
Давайте попробуем ввести в терминале пять часто используемых команд Linux (ls, pwd, uname, echo «hi» и who), поставив перед ними пробел, и проверим, будут ли эти команды сохранены в истории.
Теперь запустим команду «history», чтобы проверить, зафиксированы ли вышеприведенные команды.
Вы видите, что наши последние команды не записаны в логе. Обмануть команду «history» также можно с помощью сочетания «cat | bash».
13. Команда stat
Команда stat в Linux выводит подробную информацию о файле или файловой системе, включая размер, количество блоков, дату последнего доступа, модификации и т.д.
14. <alt>. и <esc>.
Приведенные выше сочетания клавиш на самом деле являются не командами, а твиком, подставляющим в командную строку последнюю введенную команду. Просто нажмите «Alt» или «Esc», и, продолжая удерживать клавишу, нажимайте «.».
15. Команда pv
В фильмах вы можете увидеть симулированный ввод текста, когда он появляется на экране, как будто вводится пользователем. Вы можете направить на вывод в таком режиме любой текст с помощью команды «pv». Если эта команда у вас не установлена, вы можете сделать это с помощью apt или yum.
Приведенная выше команда выводит список всех смонтированных файловых систем в форматированном виде с подробностями.
17. Команда Ctr+l
Перед тем, как пойти дальше, позвольте напомнить вам, как бысто очистить терминал. Обычно это делается с помощью команды «clear», но тот же эффект достигается с помощью клавиатурного сочетания «Ctr+l».
18. Команда curl
Как насчет проверки непрочитанных почтовых сообщений из командной строки? Эта команда очень полезна для всех, кто работает на сервере. Она запрашивает пароль непосредственно в процессе работы, поэтому вам не нужно вводить его в теле команды, повышая тем самым вероятность его компроментирования.
19. Команда screen
Команда screen дает возможность отключать от текущей сессии долго работающий запущенный процесс, чтобы он выполнялся в фоне, а затем вновь подключить его к текущей сессии.
Для запуска процесса мы обычно используем команду:
При этом пользователь должен держать данную сессию открытой до завершения работы процесса, однако мы можем также запустить вышеприведенную команду следующим образом:
После запуска команды нажмите «Ctrl + A» и затем «d», чтобы отключить процесс от текущей сессии. Он будет продолжать работать в фоновом режиме. Для того, чтобы снова подключить процесс, введите:
20. file
21. id
Эта команда выводит реальные и эффективные id пользователя и группы.
Команда Stat в Linux 2021
Использование команды stat
Синтаксис команды stat следующий:
stat принимает одно или несколько входных имен FILE и включает в себя ряд параметров, которые управляют поведением команды и выводом.
Давайте посмотрим на следующий пример:
Вывод будет выглядеть примерно так:
При вызове без каких-либо параметров stat отображает следующую информацию о файле:
Отображение информации о файловой системе
Вывод команды будет выглядеть так:
File: «package.json» ID: 8eb53097b4494d20 Namelen: 255 Type: ext2/ext3 Block size: 4096 Fundamental block size: 4096 Blocks: Total: 61271111 Free: 25395668 Available: 22265851 Inodes: Total: 15630336 Free: 13979610
Разыменование (Follow) Симлинки
По умолчанию stat не следует символическим ссылкам. Если вы запустите команду по символической ссылке, вывод будет содержать информацию о символической ссылке, а не о файле, на который она указывает:
Настройка вывода
Например, чтобы просмотреть только тип файла, который вы будете использовать:
character special file
Вы можете комбинировать любое количество директив форматирования и, при необходимости, использовать пользовательские разделители между ними. Разделитель может быть одним символом или строкой:
/dev/null, character special file
\n печатает новую строку:
Name: /etc Permissions: 755
stat также может отображать информацию в краткой форме. Этот формат полезен для анализа другими утилитами.
/etc 12288 24 41ed 0 0 801 8126465 147 0 0 1573068933 1573068927 1573068927 0 4096
Вывод
Команда stat печатает информацию о заданных файлах и файловых системах.
Команда Chmod в Linux (права доступа к файлам)
В Linux доступ к файлам управляется через права доступа к файлам, атрибуты и права собственности. В этом руководстве рассказывается, как использовать команду chmod для изменения прав доступа к файлам и каталогам.
Команда Chgrp в Linux (сменить группу)
В Linux каждый файл связан с владельцем и группой и имеет разрешения, которые определяют, какие пользователи могут читать, записывать или выполнять файл. Команда chgrpc меняет групповое владение данными файлами.
Команда cp в linux (копирование файлов)
How to Use the Linux stat command
Let’s check out how to use stat to get all the important data you need for a specific file/filesystem.
Why stat command
Sometimes, you may want to know some key details about a certain file/filesystem, for example, the file’s size, access permissions, inode number, time of last access/modification etc. Agreed, you can check out a lot of details about a file using ls. However, stat offers far more in-depth about the target file/filesystem.
When should you use stat? Whenever you need those extra information. For a quick comparison, let’s check out the file info of file1.txt. To better understand the output, learn more about the lh command.
Now, let’s check out what stat has to offer.
That’s a lot of information! You don’t need all of them in everyday life but in some specific situation, stat comes in super handy.
Linux Stat Usage: Location
Most of the Linux commands run from the /usr/bin directory.
Linux Stat Usage: Checking file/filesystem info
We’ve already seen this in action, right? The command structure goes like this.
To see the in-depth info of a file/filesystem, run this command. In this case, it’s my trusty file1.txt.
There are TONS of information about the specific file, right? All the information presented is labelled. Depending on your requirement, pick up the important one. From my experience, the most used ones are file permissions, inode and Uid and/or Gid.
Now, let’s check out an example with a filesystem. In this case, it’ll be the mount point of the filesystem. For example, this command will show the information of the root filesystem.
In Linux, (almost) every single thing is a file. Any filesystem is a file itself, so the output won’t be any different.
Linux Stat Usage: Terse form
When you’re running stat normally, all the information is printed in a human-readable structure. Want a short and simple version of the output? Add the “-t” argument.
The terse format is a special format that uses a predefined list of stat format specifiers.
Linux Stat Usage: Custom format
This is another interesting usage of the stat command where you can design the desired output structure of stat. To do this task, stat offers a LONG list of available format specifiers.
Here’s how the command looks like.
For example, the “%A” specifier returns the file/filesystem permissions in a human-readable format.
The “%U” specifier returns the owner of the file/filesystem.
To get the size of the file, use the “%s” format specifier.
Want the file type? Use “%F”.
For the inode number, use “%i”.
Now, let’s combine all of them together into a single command line. It will look like this.
There are tons of other format specifiers that stat support. All of them are listed in the man page of stats.
Now, as we’ve previously seen the “-t” or “–terse” argument, it’s a predefined value for the following arguments.
As for the “–terse –file-system” argument, the predefined value is as follows.
These outputs are very useful if you’re using stat in any sort of script, especially in bash scripts. New to bash script? Check out the beginner’s guide to bash scripting.
Printf vs format
The stat command supports –printf argument that functions basically the same manner as –format. However, the main difference between them is how the output is produced.
Let’s get it clear with an example. Here, I’m running stat with both arguments with the same format specifier.
As we can see, the –format argument adds a new line after the output ends. However, the –printf doesn’t. To make sure that there’s a new line after the output, you have to add “\n” at the end of the format specifier string.
Differentiate between file and link
In certain situations, you might be actually working with a link. However, by default, stat doesn’t differentiate between a link and a physical file. There’s a dedicated argument to get around this issue. Just pass the “-L” argument.
Final thoughts
The stat tool is a pretty straightforward one. All of its functions are managed by simple arguments and flags. Once you know which one to use, you can reap the most benefit out of it.
To learn further in-depth about the stat command, I highly recommend checking out the man page. It contains all the supported format specifiers and some additional arguments that you may find interesting.
🐧 20 команд мониторинга Linux, которые вы должны знать
Вступление
1. Top
2. vmstat
Команда vmstat – это утилита Linux для отображения статистики, связанной с потреблением памяти, использования диска и другой системной информацией.
vmstat не должен присутствовать в вашей системе Linux, но не беспокойтесь.
Мы можем легко установить пакет «sysstat»
3. iostat
Команда iostat на Linux позволяет отслеживать статистику использования ЦП и ввода-вывода ( I/O) для всех дисков и файловых систем.
Команды iostat полезны для изменения конфигурации системы, чтобы лучше сбалансировать нагрузку ввода-вывода между физическими дисками.
Эта команда в основном используется системными администраторами Linux.
5. lsof
Задача команды lsof – «перечислить открытые файлы» в системе.
Открытый файл не означает pdf или текстовый файл, он включает файлы на диске или каналы, используемые процессами в фоновом режиме.
Вывод:3
6. tcpdump
Tcpdump – это инструмент, который используется для анализа пакетов TCP / IP.
Эта команда обычно используется для анализа трафика в Linux, а также во многих других операционных системах.
tcpdump позволяет прослушивать весь входящий и исходящий трафик со всех интерфейсов.
Что еще более важно, он может фильтровать трафик по интерфейсу, хосту, месту назначения или хосту-источнику, типу трафика и многим другим критериям.
Чтобы вывести статистику только избранных протоколов, таких как TCP или UDP, используйте соответствующие параметры, такие как t и u, вместе с параметром s.
Команда ps выводит четыре столбца информации для двух минимальных процессов, запущенных в текущей оболочке.
Landoflinux
Stat command
Displaying Files and File System information
The following are examples of how to use the Linux «stat» command to display detailed information relating to files and file systems.
Linux stat command examples
The Linux stat command is a tool that can be used for displaying detailed information relating to a file or file system on a Linux system. By default the stat command should be available on most distributions of Linux. In the examples below, a CentOS Linux distribution was used.
Linux Stat Command Syntax
The basic syntax of the «statstrong>» command is as follows:
The simplest use of the «stat» command is to pass the name of a file to the command. In the example below you can see the default output from the stat command. Basic information such as size, file type, Inode information, Number of links, Access, Modification and Change date and time stamps are displayed. The stat command is often used to view Modification/access times on a file. (A more detailed way of displaying creation time and access time stamps on a file is to use the debugfs command)
If you wish to view information that relates to a file system and not an individual file, you may pass the «-f» parameter followed by a filesystem:
Format Sequences
To display specific information relating to a file or file system, you may use what is known as a format sequence. By passing the parameter «-c» or «—format» for files and «-f» or «—file-system» for file systems. You can specify individual points of interest such as inode number, mount point etc.. A list of all the parameters that can be passed for files and file systems is listed at the bottom of the page.
As an example we are specifying that we would like to display the inode information of the specified file.
From the above we can see that the inode number for the file «anaconda-ks.cfg» is «135«.
In this example we are specifying multiple format sequences that we would like to display.
In the above example, multiple parameters were passed to the «—format» option. An explanation of these is listed below:
inode number: %i
group ID of owner: %g
group name of owner: %G
file name: anaconda-ks.cfg
The output from the file indicates that the inode number is «135«, the group ID of the owner is «0» and the group name of the owner is «root«.
The above example of the stat command is used against a file system. In this example, we use the «-f» option indicating that we are passing a file system. The «-c» flag is used to specify the format sequence.
For a full list of parameters that can be used against a file system, see the list below.
Format Sequences for files
The following format sequences are for use with files:
Format Sequences for File Systems
The following format sequences are for use with File Systems:




























