- 10 lsof Command Examples in Linux
- 1. List all Open Files with lsof Command
- 2. List User Specific Opened Files
- 3. Find Processes running on Specific Port
- 4. List Only IPv4 & IPv6 Open Files
- 5. List Open Files of TCP Port ranges 1-1024
- 6. Exclude User with ‘^’ Character
- 7. Find Out who’s Looking What Files and Commands?
- 8. List all Network Connections
- 9. Search by PID
- 10. Kill all Activity of Particular User
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Использование команды lsof в Linux с примерами
- Установка lsof
- Получение помощи
- Поля вывода
- Обычное использование
- Список всех открытых файлов
- Список по имени файла
- Список открытых файлов по имени пользователя
- Список открытых файлов по процессам
- Список открытых файлов по PID
- Список открытых файлов, содержащих каталог
- Режим повторения
- Список открытых файлов по сетевому протоколу
- Список открытых файлов по портам
- Список открытых файлов по IPv4/IPv6
- Список открытых файлов в NFS
- Список заблокированных удаленных файлов
- Заключение
- Добавить комментарий Отменить ответ
- Landoflinux
- lsof command examples
- How to Install lsof on Ubuntu/Debian systems
- Install lsof on RHEL/CentOS systems
- lsof Command Examples
- List all Open Files
- lsof Column Headers
- Display a Process or User using a Mount Point
- List all processes with open files under a specified directory
- List all files in use by a specified user
- List all open files by a specific process ID
- How to automatically repeat a lsof command
- Listing Network Connections with lsof
- Listing connections on a specific port
- Listing Connections on a range of ports
- Limiting output to IPv4 or IPv6
- Identify processes not releasing space
10 lsof Command Examples in Linux
This is our on-going series of Linux commands and in this article we are going to review lsof command with practical examples. lsof meaning ‘LiSt Open Files’ is used to find out which files are open by which process. As we all know Linux/Unix considers everything as a files (pipes, sockets, directories, devices etc). One of the reason to use lsof command is when a disk cannot be unmounted as it says the files are being used. With the help of this command we can easily identify the files which are in use.
10 Linux lsof Command Examples
1. List all Open Files with lsof Command
In the below example, it will show long listing of open files some of them are extracted for better understanding which displays the columns like Command, PID, USER, FD, TYPE etc.
Sections and it’s values are self-explanatory. However, we’ll review FD & TYPE columns more precisely.
FD – stands for File descriptor and may seen some of the values as:
- cwd current working directory
- rtd root directory
- txt program text (code and data)
- mem memory-mapped file
Also in FD column numbers like 1u is actual file descriptor and followed by u,r,w of it’s mode as:
- r for read access.
- w for write access.
- u for read and write access.
TYPE – of files and it’s identification.
- DIR – Directory
- REG – Regular file
- CHR – Character special file.
- FIFO – First In First Out
2. List User Specific Opened Files
The below command will display the list of all opened files of user tecmint.
3. Find Processes running on Specific Port
To find out all the running process of specific port, just use the following command with option -i. The below example will list all running process of port 22.
4. List Only IPv4 & IPv6 Open Files
In below example shows only IPv4 and IPv6 network files open with separate commands.
5. List Open Files of TCP Port ranges 1-1024
To list all the running process of open files of TCP Port ranges from 1-1024.
6. Exclude User with ‘^’ Character
Here, we have excluded root user. You can exclude a particular user using ‘^’ with command as shown above.
7. Find Out who’s Looking What Files and Commands?
Below example shows user tecmint is using command like ping and /etc directory .
8. List all Network Connections
The following command with option ‘-i’ shows the list of all network connections ‘LISTENING & ESTABLISHED’.
9. Search by PID
The below example only shows whose PID is 1 [One].
10. Kill all Activity of Particular User
Sometimes you may have to kill all the processes for a specific user. Below command will kills all the processes of tecmint user.
Note: Here, it’s not possible to give example of all available options, this guide is only to show how lsof command can be use. You may refer man page of lsof command to know more about it. Please share it if you find this article is useful through our comment box below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Использование команды lsof в Linux с примерами
lsof — это мощная утилита, доступная для систем на базе Linux и Unix, которая буквально означает «список (из) открытых файлов».
Его основная функция — получать подробную информацию о различных типах файлов, открытых разными запущенными процессами. Эти файлы могут быть обычными файлами, каталогами, файлами блоков, сетевыми сокетами, именованными каналами и так далее.
Установка lsof
lsof не доступен по умолчанию в большинстве дистрибутивов Linux, но может быть легко установлен. Используйте следующую команду для установки lsof:
CentOS / RHEL / Fedora:
для CentOS / RHEL 8, вы можете использовать DNF команду
Получение помощи
Вы можете получить сводный список поддерживаемых lsof опций, используя -? или -h .
Чтобы проверить подробную информацию об установленной версии, используйте:
Поля вывода
Структура вывода lsof по умолчанию выглядит так:
Большинство из этих полей говорят за себя, исключением можно назвать FD и TYPE поля, которые несколько уникальны для LSOF и будут кратко рассмотрены ниже.
FD относится к номеру дескриптора файла файла, TYPE относится к типу узла, связанного с файлом. Теперь мы рассмотрим поддерживаемые значения для обоих этих полей.
FD поле может содержать следующие значения:
FD После поля следует один или несколько символов, описывающих режим, в котором открыт файл:
За символом режима для FD последующего может следовать LOCK символ, описание которого приведено ниже:
TYPE поле может содержать GDIR, GREG, VDIR, VREG, IPV4, IPV6 и т. д. Чтобы получить полный список поддерживаемых TYPE в lsof, обратитесь к его man странице.
Обычное использование
Ниже приведены некоторые примеры популярного использования команды lsof. Команда работает в разных вариантах Linux, и все аргументы командной строки, перечисленные ниже в примерах, должны работать на всех платформах, учитывая одну и ту же lsof версию.
Список всех открытых файлов
Запуск lsof без каких-либо параметров отобразит все файлы, открытые в данный момент активными процессами.
Вывод:
Список по имени файла
Чтобы перечислить все процессы, открывшие определенный файл, мы можем указать file-name в качестве аргумента:
Вывод:
Список открытых файлов по имени пользователя
В многопользовательской системе вы можете фильтровать список файлов по конкретным процессам, принадлежащим пользователям, используя -u флаг, за которым следует username .
Вывод:
В качестве альтернативы, если вы хотите перечислить файлы, которые открываются любым пользователем, кроме определенного, используйте -u флаг, за которым следует, ^username как показано ниже:
Вывод:
Один из способов использования lsof — это ситуации, когда вы хотите быстро убить все процессы определенного пользователя с помощью одной команды. Для достижения этой цели мы можем комбинировать kill с lsof как показано в примере ниже (выполнять от пользователя root):
Как видно из приведенного выше примера, мы можем использовать -t флаг для фильтрации всей другой информации, кроме process-id . Это может быть полезно при автоматизации и написании сценариев, как показано в предыдущем примере, в сочетании с kill командой.
Вывод:
С помощью lsof мы можем комбинировать несколько аргументов, используя OR логику, как показано ниже:
Вывод:
В качестве альтернативы, если вы хотите использовать AND логическое условие, используйте -a флаг.
Вывод:
Список открытых файлов по процессам
Мы также можем перечислить файлы, открытые конкретным процессом, используя -c параметр, за которым следует имя процесса.
Вывод:
Список открытых файлов по PID
В качестве альтернативы, чтобы перечислить файлы, открытые процессом, но вместо того process-name , чтобы указать его идентификатор, вы можете использовать -p флаг, за которым следует process-id .
Вывод:
- Если вы хотите перечислить все открытые файлы, кроме тех, которые были открыты определенным процессом, используйте, -p а затем ^process-id .
Список открытых файлов, содержащих каталог
Чтобы перечислить процессы, открывшие файлы в определенном каталоге, используйте D параметр, за которым следует путь к каталогу.
Вывод:
Если вы не хотите рекурсивно перечислять файлы внутри подкаталогов, используйте -d флаг, за которым следует путь к каталогу.
Вывод:
Режим повторения
lsof можно запускать в режиме повтора. В режиме повтора lsof будет генерировать и распечатывать выходные данные через равные промежутки времени. Опять же , есть два режима повтора , поддерживаемые LSOF, то есть с -r и r флаги. С -r флагом lsof повторяется до тех пор, пока не получит от пользователя сигнал прерывания/уничтожения, а с r флагом lsof Repeat режим завершится, как только на его выходе нет открытых файлов. Кроме того, мы можем указать время задержки с помощью флажка -r или r .
Вывод:
Список открытых файлов по сетевому протоколу
lsof поддерживает список всех типов файлов Linux, включая сетевые сокеты и т.д. Таким образом, мы можем перечислить детали открытых сетевых подключений, используя -i флаг.
Вывод:
Чтобы перечислить все сетевые подключения, используемые конкретным пользователем process-id , вы можете использовать lsof как:
Вывод:
Или, чтобы перечислить все сетевые соединения, используемые определенным процессом, мы можем дать следующее process-name :
Вывод:
Мы можем фильтровать вывод LSOF с -i флагом по типу сетевого протокола, то есть, TCP или UDP путем указания типа протокола.
Вывод:
Вывод:
Список открытых файлов по портам
Мы также можем фильтровать вывод lsof с помощью -i флага, port number используя синтаксис команды, как показано ниже:
Вывод:
Список открытых файлов по IPv4/IPv6
Существует возможность фильтровать список сетевых подключений, ограничивая его IPv4 или IPv6. Используйте приведенный ниже синтаксис команды, чтобы получить только список IPv4:
Вывод:
ИЛИ, чтобы получить информацию только о IPv6, используйте:
Вывод:
Список открытых файлов в NFS
lsof также может вывести список всех файлов NFS, открытых в данный момент пользователем.
Список заблокированных удаленных файлов
Иногда случается, что в Linux файлы удаляются, но по-прежнему блокируются одним или несколькими процессами. Таким образом, эти файлы не отображаются в обычном листинге файловой системы с помощью ls команды и т.д., Но они по-прежнему занимают дисковое пространство, как указано в выводе df , это происходит особенно с большими файлами, удаленными с целью очистить дисковое пространство без снятия блокировки процесса. Вы можете найти такие процессы, используя lsof как:
Вывод:
Заключение
lsof предлагает ряд опций для настройки вывода в соответствии с вашими потребностями. Это полезная утилита в повседневных задачах системного и сетевого администрирования . Возможность комбинировать различные аргументы делает его еще более полезным и позволяет легко получить требуемый результат. Обратитесь к странице руководства lsof, чтобы узнать обо всех поддерживаемых аргументах и их использовании.
Добавить комментарий Отменить ответ
Для отправки комментария вам необходимо авторизоваться.
Источник
Landoflinux
lsof command examples
lsof is a command that is used to display «open files» and the process that is responsible for opening the file. With no parameters passed, «lsof» will list all open files and associated processes currently running. lsof can be used to identify which ports are currently open and by what processes, list all network connections, list users and processes who are currently accessing directories or files and identify processes that are utilizing space within a filesystem. For a full list of all the options and functions that are available to the «lsof» command, please consult the man pages.
Below are a examples of the «lsof» command and how to install lsof on Ubuntu/RHEL/Fedora systems.
How to Install lsof on Ubuntu/Debian systems
Generally lsof is installed by default on most Ubuntu and Debian based systems (MATE, Mint etc..), however, if you need to install «lsof», you can issue the commands below:
The «sudo apt update» command will update your repositories. The «sudo apt install lsof» command will install the lsof package. To verify the version after installation, you may issue the «lsof -v» command.
Install lsof on RHEL/CentOS systems
lsof Command Examples
Below are some useful examples of the «lsof» command in use. These examples were all carried out using a CentOS based system.
List all Open Files
Below is a small extract of the output from the command «lsof» running on a standard «CentOS». (Please note for clarity, many lines have been omitted).
By default 1 file per line is displayed. The output is organized into columns. Below are some of the frequently used fields that you will need to know about:
lsof Column Headers
COMMAND — Name of Process running
PID — Process Identification Number
USER — Process Owner
FD — Field Descriptor
cwd — Current Working Directory
rtd — Root Directory
txt — Text File
mem — Memory Mapped File
mmap — Memory Mapped Device
Number — Represents the file Descriptor. After the number a character is used to indicate the mode to which the file was opened:
examples:
1u — u = Read Access and Write Access
1r — r = Read Access
1w — w = Write Access
TYPE — Type — Specifies file type such as: REG (regular file), DIR (Directory, FIFO (First in First Out), CHR (Character Special File)
Display a Process or User using a Mount Point
Quite often as an Administrator you will need to unmount a filesystem if its no longer needed or for maintenance purposes. If you issue the standard «umount» command, you may encounter the error/warning indicating that the current target or mount point can not be unmounted as its busy (currently in use by a process/user):
In the following example, we have a user called «john» who is currently accessing the mount point «/test». We will try to unmount this filesystem:
As the error suggests, the mount point is busy (in use or being accessed). However, we can use the «lsof» command to identify who or what is using this mount point:
From the above we can see that we have a user «john» who is accessing the «/test» area. We can see from the output that this is indicated by the DIR, NAME and cwd entries. We can also see that the user is using the «bash» shell to access this area. The process Identification (PID) is also indicated.
So for the administrator to unmount this file system, they will need the user to come out of that particular area or kill the identified PID/Process. Once the user has moved out of this mount point, you should now be able to unmount the area without issue.
List all processes with open files under a specified directory
In the following example, we use the lsof command to identify all process that are accessing the specified directory structure and sub-directories. The «+D» causes lsof to search for all open instances of the specified directory and its sub-directories.
From the above output we can see which processes or users are accessing the specified path and its sub-directories.
List all files in use by a specified user
To list all files that are currently open for a specified user. We can pass the «-u» parameter followed by the «userid«.
In the example below, we can see all files that are open by the user «john». If you wish to exclude a particular user from the output, you may modify the command to be: «lsof -u ^john«.
List all open files by a specific process ID
The «-p» parameter when passed is used to specify a particular process. In the example below, we are only outputting information that is associated with the Process (PID) «1591»:
How to automatically repeat a lsof command
A useful option that can be used in conjunction with the «lsof» command is the «-r» parameter followed by a time duration. If no time duration is passed, then the default of 15 seconds will be used. This parameter when specified instructs lsof to repeat the command at the specified time interval. In the example below we are repeating the command every 5 seconds.
The output is divided by the following line separator «=======»
Listing Network Connections with lsof
To list all network connections on your system you can issue the lsof command with the «-i» parameter. If you want to see only TCP connections, you can use «lsof -i tcp» and for «UDP» connection you can issue the command «lsof -i udp«.
In the above example we can see all our active connections along with their protocol and name.
Listing connections on a specific port
To display a specific port and look for connections/processes, you may issue the command «lsof -i:port_number«.
In the example below, we have specified port 22. This is the default port for ssh connections. We can see from the output that the ssh daemon is listening on port 22 for connections and that a connection has been established from the remote IP address of «192.168.0.23».
You also issue the command specifying a process to look for. In this example, we have specified the string «ssh» and «httpd«:
Listing Connections on a range of ports
To specify a range of ports, we can specify the range of ports to check. In the example below, we are checking for all connections on ports 22 through to 25.
Limiting output to IPv4 or IPv6
To limit the output from the lsof command to either IPv4 or IPv6, you can pass the parameter «-i4» for IPv4 and «-i6» for IPv6 only.
Identify processes not releasing space
On occasion, you may notice that the «df» command reports that you have less space available within a filesystem. When you look for files that are using space using conventional commands like «ls» and «du», you will find that there are no listed files consuming space. You cannot visibly see any files that are consuming space. The «lsof» command can help here as it will allow you to identify unlinked files that are holding onto space.
A technique often used within programming is to create a temporary file and then unlink the file. This coding technique will leave the file and its available space available to the executing program. Sometimes programmes do not exit cleanly and can leave these unlinked files holding onto space. To determine if you have a process holding onto an unlinked file, you can issue the following command:
lsof -a +L1 /your/filesystem
From the output, you should look for any processes that have a zero «0» value under the NLINK column. To release the space occupied by these processes, you will need to kill (terminate) the process that has been identified under the PID column. The amount of space can be identified under the SIZE heading column. Once the process has been killed, the space will now become usable and will be correctly reported by the «df» command.
Below is an example of output from the lsof command displaying the unlinked files:
Источник