Show all open files linux

Содержание
  1. Linux: Show Opened Files, lsof
  2. Вики IT-KB
  3. Инструменты пользователя
  4. Инструменты сайта
  5. Боковая панель
  6. Содержание
  7. Как проверить все открытые файлы пользователем или процессом в Linux
  8. Лимит ядра Linux
  9. Методика подсчёта открытых файлов
  10. Примеры получения данных
  11. How to use the Linux ‘lsof’ command to list open files
  12. lsof command background
  13. I assume you’re logged in as root
  14. Basic Linux lsof command examples
  15. Common lsof options
  16. Summary: Linux lsof command examples
  17. 15 Linux lsof Command Examples (Identify Open Files)
  18. 1. Introduction to lsof
  19. 2. List processes which opened a specific file
  20. 3. List opened files under a directory
  21. 4. List opened files based on process names starting with
  22. 5. List processes using a mount point
  23. 6. List files opened by a specific user
  24. 7. List all open files by a specific process
  25. 8. Kill all process that belongs to a particular user
  26. 9. Combine more list options using OR/AND
  27. 10. Execute lsof in repeat mode
  28. Finding Network Connection
  29. 11. List all network connections
  30. 12. List all network files in use by a specific process
  31. 13. List processes which are listening on a particular port
  32. 14. List all TCP or UDP connections
  33. 15. List all Network File System ( NFS ) files
  34. How to Check Open Files in Linux
  35. Pre-Requisites
  36. LSOF Utility
  37. How to Install lsof on Debian/Ubuntu
  38. How to Install on REHL/CentOS
  39. How to Install on Arch
  40. How to Install on Fedora
  41. Basic lsof Usage
  42. How to Show Processes that Opened a File
  43. How Show files Opened by a Specific User
  44. How to Show Files Opened by a Specific Process
  45. How to Show Files Opened in a Directory
  46. How to Show Network Connection
  47. How to Continuously Show Files
  48. Conclusion
  49. About the author
  50. John Otieno

Linux: Show Opened Files, lsof

You can use the command lsof to list all files opened by processes.

In unix/linux, “everything” is a file. Devices (such as all USB device) are files, network sockets are files, directory is a file.

Here’s some of the commonly used options.

lsof -h Display a short help documentation. lsof fpath Show all that has opened file at fpath lsof -i List files associated with internet (For example, browser process) lsof -u userName Show all with login/uid userName lsof -p pid By pid. 123,^456 lsof +d dir By dir path dir lsof +D dir By dir path dir , also show all dir’s children lsof -c cmd Show files opened by command whose name starts with cmd lsof showing first few files opened by firefox

FD means “file descriptor”. Common FD code are:

cwd Current working directory ltx Shared library text (code and data) m86 DOS Merge mapped file mem Memory-mapped file mmap Memory-mapped device pd Parent directory rtd Root directory txt Program text (code and data) number File descriptor. 0 is stdin, 1 is stdout, 2 is stderr. A letter after it means mode. “u” = read and write. “r” = read. “w” = write.

see man lsof for complete list and description.

TYPE в†’ is the file type. Common types are:

REG Regular file LINK Symbolic link file DIR Directory BLK Block special file (device file) CHR Character special file (device file) FIFO FIFO special file PIPE Pipes PMEM /proc memory image file IPv4 IPv4 socket IPv6 Open IPv6 network file — even if its address is IPv4, mapped in an IPv6 address inet Internet domain socket sock Socket of unknown domain unix UNIX domain socket

Источник

Вики IT-KB

Пошаговые руководства, шпаргалки, полезные ссылки.

Инструменты пользователя

Инструменты сайта

Боковая панель

Содержание

Как проверить все открытые файлы пользователем или процессом в Linux

В некоторых ситуациях на Linux могут возникать ошибки, связанные с превышением лимита использования файловых дескрипторов. Эти лимиты накладываются как самим ядром Linux, так и его программными модулями, например PAM.

Лимит ядра Linux

Узнать текущее значение максимального количества файловых дескрипторов, определяемое ядром Linux можно командой:

Этот лимит может быть изменён без перезагрузки системы (начинает действовать сразу и действует до перезагрузки):

Чтобы требуемое значение использовалось постоянно, то есть действовало и после перезагрузки, его необходимо определить в конфиг.файле /etc/sysclt.conf :

Методика подсчёта открытых файлов

Для получения информации о количестве всех открытых файлов всеми процессами в Linux некоторые «знатоки» предлагают использовать команду типа

Однако такая команда показывает гораздо большее значение, чем всего открыто файлов в системе на данный момент на самом деле. Это связано с тем, что по несколько раз в подсчёт попадают одни и теже открытые файлы, используемые разными процессами.

Поэтому проще для получения общего числа открытых файлов использовать данные ядра Linux

Первое число — общее количество занятых/используемых на данный момент времени файловых дескрипторов.
Второе число — количество выделенных процессам, но не используемых в данный момент дескрипторов.
Третье число — максимальное количество открытых дескрипторов

Примеры получения данных

Получить список TOP-20 процессов с самым большим количеством открытых файловых дескрипторов:

Подсчитать количество открытых файлов в разрезе процессов (в первой колонке будет выведен PID процесса, во второй количество открытых файлов этим процессом):

Посмотреть открытые файловые дескрипторы во всех процессах для отдельно взятого пользователя, например «apache»

Подсчитать количество открытых файлов в каждом процессе для отдельно взятого пользователя:

Тоже самое, только в реальном режиме времени:

Посмотреть открыте файловые дескриптры для отдельно взятого процесса (по PID процесса):

Подсчитать количество файловых дескриптров для отдельно взятого процесса:

Дополнительные источники информации:

Проверено на следующих конфигурациях:

Версия ОС
Debian GNU/Linux 8.10 (jessie)

Автор первичной редакции:
Алексей Максимов
Время публикации: 09.06.2018 11:18

Источник

How to use the Linux ‘lsof’ command to list open files

Linux “open files” FAQ: Can you share some examples of how to show open files on a Linux system (i.e., how to use the lsof command)?

lsof command background

The Linux lsof command lists information about files that are open by processes running on the system. The lsof command is an acronym for, “list of open files.” In this article I’ll share some lsof command examples.

I assume you’re logged in as root

One other note: In these examples I’ll assume that you’re logged in as the Unix/Linux root user. If not, you’re lsof command output may be significantly limited. If you’re logged in as a non-root user, either su to root, or use sudo to run these commands.

Basic Linux lsof command examples

Typing the lsof command by itself lists all open files belonging to all active processes on the system:

On my current macOS system, which has been running for a long time, this shows a lot of open files, 1,582 to be specific:

Note that I didn’t have to be logged in as the root user to see this information on my Mac system.

Adding the head command to lsof shows what some of this output looks like:

Common lsof options

As mentioned, these details go on for 1,582 lines, so it helps to have some way to weed through that output, whether that involves using the grep command, or some of the lsof options shown below.

This command lists all open files belonging to PID (process ID) 11925 :

This command lists all open files belonging to processes owned by the user named «al»:

This command lists files that are open in the directory specified, but it does not descend into sub-directories:

The next command lists files that are open in the directory specified, and also descends into sub-directories. Beware: this can take a very long time to run for large directory structures:

Summary: Linux lsof command examples

I hope these Linux lsof command examples have been helpful. As you can see, the lsof command can be used to generate a list of open files on your Unix and Linux system with a variety of different command line options for different circumstances.

For more information on the lsof command, please see the «Related» block on this page, follow this link to lsof command search results on this website, or leave a note in the Comments section below.

Источник

15 Linux lsof Command Examples (Identify Open Files)

lsof stands for List Open Files.

It is easy to remember lsof command if you think of it as “ls + of”, where ls stands for list, and of stands for open files.

It is a command line utility which is used to list the information about the files that are opened by various processes. In unix, everything is a file, ( pipes, sockets, directories, devices, etc.). So by using lsof, you can get the information about any opened files.

1. Introduction to lsof

Simply typing lsof will provide a list of all open files belonging to all active processes.

By default One file per line is displayed. Most of the columns are self explanatory. We will explain the details about couple of cryptic columns (FD and TYPE).

FD – Represents the file descriptor. Some of the values of FDs are,

  • cwd – Current Working Directory
  • txt – Text file
  • mem – Memory mapped file
  • mmap – Memory mapped device
  • NUMBER – Represent the actual file descriptor. The character after the number i.e ‘1u’, represents the mode in which the file is opened. r for read, w for write, u for read and write.

TYPE – Specifies the type of the file. Some of the values of TYPEs are,

  • REG – Regular File
  • DIR – Directory
  • FIFO – First In First Out
  • CHR – Character special file

For a complete list of FD & TYPE, refer man lsof.

2. List processes which opened a specific file

You can list only the processes which opened a specific file, by providing the filename as arguments.

3. List opened files under a directory

You can list the processes which opened files under a specified directory using ‘+D’ option. +D will recurse the sub directories also. If you don’t want lsof to recurse, then use ‘+d’ option.

4. List opened files based on process names starting with

You can list the files opened by process names starting with a string, using ‘-c’ option. -c followed by the process name will list the files opened by the process starting with that processes name. You can give multiple -c switch on a single command line.

5. List processes using a mount point

Sometime when we try to umount a directory, the system will say “Device or Resource Busy” error. So we need to find out what are all the processes using the mount point and kill those processes to umount the directory. By using lsof we can find those processes.

The following will also work.

6. List files opened by a specific user

In order to find the list of files opened by a specific users, use ‘-u’ option.

Sometimes you may want to list files opened by all users, expect some 1 or 2. In that case you can use the ‘^’ to exclude only the particular user as follows

The above command listed all the files opened by all users, expect user ‘lakshmanan’.

7. List all open files by a specific process

You can list all the files opened by a specific process using ‘-p’ option. It will be helpful sometimes to get more information about a specific process.

8. Kill all process that belongs to a particular user

When you want to kill all the processes which has files opened by a specific user, you can use ‘-t’ option to list output only the process id of the process, and pass it to kill as follows

The above command will kill all process belonging to user ‘lakshmanan’, which has files opened.

Similarly you can also use ‘-t’ in many ways. For example, to list process id of a process which opened /var/log/syslog can be done by

Talking about kill, did you know that there are 4 Ways to Kill a Process?

9. Combine more list options using OR/AND

By default when you use more than one list option in lsof, they will be ORed. For example,

The above command uses two list options, ‘-u’ and ‘-c’. So the command will list process belongs to user ‘lakshmanan’ as well as process name starts with ‘init’.

But when you want to list a process belongs to user ‘lakshmanan’ and the process name starts with ‘init’, you can use ‘-a’ option.

The above command will not output anything, because there is no such process named ‘init’ belonging to user ‘lakshmanan’.

10. Execute lsof in repeat mode

lsof also support Repeat mode. It will first list files based on the given parameters, and delay for specified seconds and again list files based on the given parameters. It can be interrupted by a signal.

Repeat mode can be enabled by using ‘-r’ or ‘+r’. If ‘+r’ is used then, the repeat mode will end when no open files are found. ‘-r’ will continue to list,delay,list until a interrupt is given irrespective of files are opened or not.

Each cycle output will be separated by using ‘=======’. You also also specify the time delay as ‘-r’ | ‘+r’.

In the above output, for the first 5 seconds, there is no output. After that a script named “inita.sh” is started, and it list the output.

Finding Network Connection

Network connections are also files. So we can find information about them by using lsof.

11. List all network connections

You can list all the network connections opened by using ‘-i’ option.

You can also use ‘-i4’ or ‘-i6’ to list only ‘IPV4’ or ‘IPV6‘ respectively.

12. List all network files in use by a specific process

You can list all the network files which is being used by a process as follows

You can also use the following

The above command will list the network files opened by the processes starting with ssh.

13. List processes which are listening on a particular port

You can list the processes which are listening on a particular port by using ‘-i’ with ‘:’ as follows

14. List all TCP or UDP connections

You can list all the TCP or UDP connections by specifying the protocol using ‘-i’.

15. List all Network File System ( NFS ) files

You can list all the NFS files by using ‘-N’ option. The following lsof command will list all NFS files used by user ‘lakshmanan’.

Источник

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:

  • A Linux system
  • User with root or sudo privileges

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 update

sudo apt-get install lsof -y

How to Install on REHL/CentOS

To install on REHL and CentOS, use the command:

sudo dnf update

sudo dnf install lsof

How to Install on Arch

On Arch, call the package manager using the command:

sudo pacman -S lsof

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.

We can use the command:

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

Источник

Читайте также:  Настройка прокси сервера linux centos
Оцените статью