- How to List Open Files on Ubuntu
- List All Open Files
- Listing Files Opened by User
- Вики IT-KB
- Как проверить все открытые файлы пользователем или процессом в Linux
- Лимит ядра Linux
- Методика подсчёта открытых файлов
- Примеры получения данных
- Обсуждение
- How to Check Open Files in Linux
- Pre-Requisites
- LSOF Utility
- How to Install lsof on Debian/Ubuntu
- How to Install on REHL/CentOS
- How to Install on Arch
- How to Install on Fedora
- Basic lsof Usage
- How to Show Processes that Opened a File
- How Show files Opened by a Specific User
- How to Show Files Opened by a Specific Process
- How to Show Files Opened in a Directory
- How to Show Network Connection
- How to Continuously Show Files
- Conclusion
- About the author
- John Otieno
How to List Open Files on Ubuntu
In this tutorial, you will learn how to list open files on your Ubuntu servers using the lsof command.
The are a number of scenarios where you, a system administrator, will need to know what files are in use by your users or services. It could be to discover which files are open on a volume that needs to be unmounted for maintenance, or to ensure a service is running correctly, for example.
List All Open Files
In the first example, a listing all of open files by all users will be generated with the lsof command.
The output will look similar to the following.
COMMAND PID TID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd 1 root cwd DIR 202,1 4096 2 / systemd 1 root rtd DIR 202,1 4096 2 / systemd 1 root txt REG 202,1 1595792 19540 /lib/systemd/systemd systemd 1 root mem REG 202,1 1700792 2083 /lib/x86_64-linux-gnu/libm-2.27.so systemd 1 root mem REG 202,1 121016 16613 /lib/x86_64-linux-gnu/libudev.so.1.6.9 systemd 1 root mem REG 202,1 84032 2068 /lib/x86_64-linux-gnu/libgpg-error.so.0.22.0 systemd 1 root mem REG 202,1 43304 2212 /lib/x86_64-linux-gnu/libjson-c.so.3.0.1 systemd 1 root mem REG 202,1 34872 6169 /usr/lib/x86_64-linux-gnu/libargon2.so.0 systemd 1 root mem REG 202,1 432640 2208 /lib/x86_64-linux-gnu/libdevmapper.so.1.02.1 [ truncated results ]
Listing Files Opened by User
Another example is listing files opened only by a specific user. The -u flag is used with the lsof command to filter the list for a specified user. For example, here is an example of the command for a user named www-data.
The user is for an Apache2 web server, and the resulting list would look similar to the following. The results have been truncated, as the listing can get quite long.
COMMAND PID TID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd 1 root cwd DIR 202,1 4096 2 / systemd 1 root rtd DIR 202,1 4096 2 / systemd 1 root txt REG 202,1 1595792 19540 /lib/systemd/systemd systemd 1 root mem REG 202,1 1700792 2083 /lib/x86_64-linux-gnu/libm-2.27.so systemd 1 root mem REG 202,1 121016 16613 /lib/x86_64-linux-gnu/libudev.so.1.6.9 systemd 1 root mem REG 202,1 84032 2068 /lib/x86_64-linux-gnu/libgpg-error.so.0.22.0 systemd 1 root mem REG 202,1 43304 2212 /lib/x86_64-linux-gnu/libjson-c.so.3.0.1 systemd 1 root mem REG 202,1 34872 6169 /usr/lib/x86_64-linux-gnu/libargon2.so.0 systemd 1 root mem REG 202,1 432640 2208 /lib/x86_64-linux-gnu/libdevmapper.so.1.02.1
Вики IT-KB
Как проверить все открытые файлы пользователем или процессом в Linux
В некоторых ситуациях на Linux могут возникать ошибки, связанные с превышением лимита использования файловых дескрипторов. Эти лимиты накладываются как самим ядром Linux, так и его программными модулями, например PAM.
Лимит ядра Linux
Узнать текущее значение максимального количества файловых дескрипторов, определяемое ядром Linux можно командой:
Этот лимит может быть изменён без перезагрузки системы (начинает действовать сразу и действует до перезагрузки):
# echo "1221724" > /proc/sys/fs/file-max
Чтобы требуемое значение использовалось постоянно, то есть действовало и после перезагрузки, его необходимо определить в конфиг.файле /etc/sysclt.conf :
Методика подсчёта открытых файлов
Для получения информации о количестве всех открытых файлов всеми процессами в Linux некоторые «знатоки» предлагают использовать команду типа
Однако такая команда показывает гораздо большее значение, чем всего открыто файлов в системе на данный момент на самом деле. Это связано с тем, что по несколько раз в подсчёт попадают одни и теже открытые файлы, используемые разными процессами.
Поэтому проще для получения общего числа открытых файлов использовать данные ядра Linux
# cat /proc/sys/fs/file-nr 5248 0 610862
Первое число — общее количество занятых/используемых на данный момент времени файловых дескрипторов.
Второе число — количество выделенных процессам, но не используемых в данный момент дескрипторов.
Третье число — максимальное количество открытых дескрипторов
Примеры получения данных
Получить список TOP-20 процессов с самым большим количеством открытых файловых дескрипторов:
# for x in `ps -eF| awk '< print $2 >'`; \ do echo `ls /proc/$x/fd 2> /dev/null | \ wc -l` $x `cat /proc/$x/cmdline 2> /dev/null`; \ done | sort -n -r | head -n 20
Подсчитать количество открытых файлов в разрезе процессов (в первой колонке будет выведен PID процесса, во второй количество открытых файлов этим процессом):
# ps aux | sed 1d | awk \ '' | \ xargs -I <> bash -c <>
Посмотреть открытые файловые дескрипторы во всех процессах для отдельно взятого пользователя, например «apache»
Подсчитать количество открытых файлов в каждом процессе для отдельно взятого пользователя:
# lsof -u apache | awk '' | sort | uniq -c | sort -n
Тоже самое, только в реальном режиме времени:
# watch 'lsof -u vdsm | awk '\'''\'' | sort | uniq -c | sort -n'
Посмотреть открыте файловые дескриптры для отдельно взятого процесса (по PID процесса):
Подсчитать количество файловых дескриптров для отдельно взятого процесса:
Дополнительные источники информации:
Проверено на следующих конфигурациях:
Автор первичной редакции:
Алексей Максимов
Время публикации: 09.06.2018 11:18
Обсуждение
unix-linux/linux-cli-tools/how-to-check-all-open-files-by-process-or-user-in-linux.txt · Последнее изменение: 09.06.2018 12:49 — Алексей Максимов
How to Check Open Files in Linux
You may have come across the saying, “Everything is a file in Linux.” Although this is not entirely true, it does hold a set of truths to it.
In Linux and Unix-like systems, everything is like a file. That means the resources in the Unix system get assigned a file descriptor, including storage devices, network sockets, processes, etc.
A file descriptor is a unique number that identifies a file and other input/output devices. It describes resources and how the kernel accesses them. Think of it as a gateway to the Kernel abstraction hardware resources.
Unfortunately, the concept of file descriptors is beyond the scope of this tutorial; consider the link provided below to get started on learning more:
That means that Unix and Unix-like systems such as Linux use such files heavily. As a Linux power user, seeing the open files and the process and users using them is incredibly useful.
This tutorial will focus on ways to view the files open and which process or user is responsible.
Pre-Requisites
Before we begin, ensure that you have:
If you have these, let us get started:
LSOF Utility
Created by Victor A Abell, List open files, or lsof for short, is a command-line utility that allows us to view the open files and the processes or users who opened them.
The lsof utility is available in major Linux distributions; however, you may find it not installed and thus may need to install manually.
How to Install lsof on Debian/Ubuntu
To install it on Debian, use the command:
sudo apt-get install lsof -y
How to Install on REHL/CentOS
To install on REHL and CentOS, use the command:
How to Install on Arch
On Arch, call the package manager using the command:
How to Install on Fedora
On Fedora, use the command:
Once you have the lsof utility installed and updated, we can begin using it.
Basic lsof Usage
To use the lsof tool, enter the command:
Once you execute the above command, lsof will dump a lot of information as shown below:
The above output shows all the files opened by the processes. The output has various columns, each representing specific information about the file.
- The COMMAND column – shows the name of the process that is using the file.
- PID – shows the Process Identifier of the process using the file.
- The TID – Shows the task ID (threads) of the process.
- TASKCMD – Represent the name of the task command.
- USER – The owner of the process.
- FD – Shows the file descriptor number. This is how processes use the file; the options available in this column output include:
- cwd – current working directory.
- mem – memory-mapped file
- pd – parent directory
- jld – jail directory
- ltx – shared library text
- rtd – root directory.
- txt – program code and data
- tr – kernel trace file.
- err – File descriptor information error
- mmp – Memory-mapped device.
- TYPE – Shows the type of node associated with the file, such as:
- Unix – for Unix domain socket.
- DIR – represents the directory
- REG – representing the regular file
- CHR – represents the special character file.
- LINK – symbolic link file
- BLK – Block special file
- INET – Internet domain socket
- FIFO – a named pipe (First In First Out file)
- PIPE – for pipes
- DEVICES – Shows the device numbers separated by commas in the order of special character file, block special, regular, directory, and NFS file.
- SIZE/OFF – shows the size of the file pr file offset in bytes.
- NODE – shows the node number of the local file, type for internet protocol type, etc.
- NAME – shows the name of the mount point and fs on which the file is located.
Note: Please Refer to the lsof Manual for detailed information on the columns.
How to Show Processes that Opened a File
Lsof provides us with options that help us filter the output to show only the processes that opened a specific file.
For example, to see the file that opened the file /bin/bash, use the command as:
This will give you an output as shown below:
COMMAND PID USER FD TYPE DEVICE SIZE / OFF NODE NAME
ksmtuned 1025 root txt REG 253 , 0 1150704 428303 / usr / bin / bash
bash 2968 centos txt REG 253 , 0 1150704 428303 / usr / bin / bash
bash 3075 centos txt REG 253 , 0 1150704 428303 / usr / bin / bash
How Show files Opened by a Specific User
We can also filter the output to show the files opened by a specific user. We do this by using the -u flag followed by the username as:
This will give you an output as shown below:
How to Show Files Opened by a Specific Process
Suppose we want to view all the files opened by a specific process? For this, we can use the PID of the process to filter the output.
For example, the below command shows the files opened by bash.
This will give you only the files opened by systemd as shown:
How to Show Files Opened in a Directory
To get the files opened in a specific directory, we can pass the +D option followed by the directory path.
For example, list open files in the /etc directory.
Below is the output for this:
How to Show Network Connection
Since everything in Linux is a file, we can get the network files such as TCP files or connections.
This will give you the TCP connections in the system.
You can also filter by the specific port using the command shown below:
This will give you the output as shown below:
How to Continuously Show Files
Lsof provides us with a mode to loop the output every few seconds. This allows you to monitor the files opened by a process or user continuously.
This option, however, requires you to terminate the process manually.
For example, the command below continuously monitors the files opened on port 22:
As you can see, in the third loop, lsof catches the established connection to the server on SSH.
Conclusion
Lsof is an incredibly useful utility. It allows you to monitor for critical files as well as monitor users and processes opening files. This can be incredibly useful when troubleshooting or looking for malicious attempts to the system.
As shown in this tutorial, using various examples and methods, you can combine the functionality provided by the lsof tool for custom monitoring.
Thank you for reading and sharing! I hope you learned something new!
About the author
John Otieno
My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list