Find opened files linux

Идентификация открытых файлов и сетевых подключений в Linux — lsof (примеры)

Lsof расшифровывает как List Open Files (список открытых файлов). Команда формирует список дескрипторов открытых файлов по процессам и именам файлов. В Линукс все является файлами (очереди, сокеты, директории, устройства и т.д. ). Таким образом, с помощью Lsof, вы можете получить информацию о любых открытых файлов.

1. Введение в lsof

Также работает рекурсивный просмотр:

6. Просмотр файлов открытых конкретным пользователем

Для поиска файлов открытых определенным пользователем, используем ключ -u

Иногда необходимо вывести файлы открытые всеми пользователями, за исключением конкретного. Для этого используется -‘^’

Данная команда выводит список файлов открытых всеми пользователями, за исключением пользователя alex1812

7. Список всех файлов открытых конкретным процессом

Для вывода списка всех файлов открытых конкретным процессов используется ключ -p. Это может быть полезно для получения большей информации о самом процессе.

8. Уничтожить все процессы используемые конкретным пользователем

Если необходимо уничтожить все процессы, имеющие открытые файлы, конкретного пользователя, мы можем использовать ключ -t для просмотра id процессов и уничтожить их с помощью kill —

Данная команда уничтожит все процессы пользователя alex1812, которые имели открытые файлы.

Аналогичным образом, вы можете использовать ключ -t для других целей, например, чтобы получить список id процессов, которые открыли /var/log/syslog

9. Комбинирование ключей

По умолчанию, если вы используете более одного ключа в Lsof, то вывод команды будет объеденен по этим ключам. Например,

В этой команде мы используем два ключа -u и -c, таким образом команда одновременно выводит и список процессов принадлежащих пользователю alex1812, и процессы начинающиеся со слова init (принадлежащих любым пользователям).

Вы можете использовать ключ -a, чтобы совместить вывод по нескольким параметрам, например процессы принадлежащие пользователю alex1812 и начинающиеся с init:

10. Выполнение Lsof в режим повтора

Lsof поддерживает вывод в режиме повтора. То бишь сначала будет выведет список файлов с заданными параметрами, затем задержка на заданный интервал и опять вывод на основе этих же параметров.

Режим повтора может быть включен ключами +r и -r. Если используем +r, то режим повтора будет прерван в случае отсутствия открытых файлов. Ключ -r будет продолжать вывод с заданным интервалом вне зависимости от наличия открытых файлов.

Каждый цикл вывода будет разделен с помощью «=======». Мы также можем указать время задержки для обоих ключей.

В данном примере мы выводим список процессов принадлежащих alex1812 c именем x-session и задержкой повторного вывода в 5 секунд.

Поиск сетевых подключений

Сетевые соединения в Linux также являются файлами. Таким образом, мы можем найти информацию о них с помощью Lsof.

11. Просмотр всех сетевых подключений

Для просмотра всех сетевых подключений используем ключ -i

Вы также можете использовать -i4 и i6 для вывода только подключений по IPv4 или IPv6 соответственно.

12. Список всех сетевых файлов используемых конкретным процессом

В первом случае мы задаем процесс по его id, во втором по имени (по первым символам).

13. Список процессов прослушивающих определенный порт

Для этого используется ключ -i и номер порта через ‘:’

14. Список всех UDP и TCP соединений

Для вывода такого списка используем —

15. Просмотр всех NFS (Network File System) файлов

Для просмотра всех NFS файлов используем ключ -N, например просмотр всех NFS файлов открытых от пользователя alex1812 —

Надеюсь информация данной статьи будет кому-либо полезна, особенно тем, кто не любит читать man’ы =)

Источник

Linux / UNIX List Open Files for Process

H ow do I list all open files for a Linux or UNIX process using command line options? How can I show open files per process under Linux?

Both Linux and Unix-like operating systems come with various utilities to find out open files associated with the process.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements None
Est. reading time 3 minutes

UNIX List Open Files For Process

First use the ps command command to get PID of process, enter:
$ ps -aef | grep $ ps -aef | grep httpd
Next pass this PID to pfiles command under Solaris Unix:
$ pfiles
$ pfiles 3533
See pfiles command documentation> for more information or type the following man command:
% man pfiles

FreeBSD list open files per process

On FreeBSD use the fstat command along with the ps command:
# ps aux | grep -i openvpn # filter outputs using the grep command #
# fstat -p
# fstat -p 1219
We can count open files count for openvpn process as follows using the wc command:
# fstat -p 1219 | grep -v ^USER | wc -l
The -p option passed to the fstat to report all files open by the specified process.

FreeBSD pstat command in action

Linux List Open Files For Process

First you need to find out PID of process. Simply use any one of the following command to obtain process id:
# ps aux | grep OR
$ ps -C -o pid=
For example, find out PID of firefox web-browser, enter:
$ ps -C firefox -o pid=
Output:

To list opne files for firefox process, enter:
$ ls -l /proc/7857/fd
Sample output:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

For privileged process use the sudo command and to count open files use the wc command on Linux as follows:
# Get process pid
sudo ps -C Xorg -o pid
sudo ls -l /proc/$/fd
# Say pid is 9497 for Xorg, then
sudo ls -l /proc/9497/fd | wc -l
We can use bash for loop as follows too:

Listing Open Files on Linux

Using lsof to display the processes using the most file handles

The lsof command list open files under all Linux distributions or UNIX-like operating system. Type the following command to list open file for process ID 351:
$ lsof -p 351
In this example display and count all open files for top 10 processes on Linux operating systems or server:
# lsof | awk ‘‘ | sort | uniq -c | sort -r | head
## force numeric sort by passing the ‘-n’ option to the sort ##
# lsof | awk ‘‘ | sort | uniq -c | sort -r -n | head

  • lsof – Run the lsof to display all open files and send output to the awk
  • awk ‘ – Display first field i.e. process name only
  • uniq -c – Omit duplicate lines while prefix lines by the number of occurrences
  • sort -r – Reverse sort
  • head – Display top 10 process along with open files count

Conclusion

Now you know how to find open files per process on Linux, FreeBSD, and Unix-like systems using various command-line options. See how to increase the system-wide/user-wide number of available (open) file handles on Linux for more information.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Вики 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.

Источник

Find Open Files in Linux

Jarret W. Buse

Guest

Find Open Files in Linux

Sometimes within any Operating System (OS), it is difficult to know when you have a file opened which needs to be managed in some way. There is nothing more stressful than trying to delete, cut or modify a file and get the error that the file is already open. Another possibility is trying to unmount a device and you get the error that the device is busy, which is usually due to an open file on the device.

So, let’s look at how to find open files because you really do not want to have to close all your open applications to get the right one.

Let’s assume I am trying to unmount sda2 and I get an error:

umount: /media/sda2: device is busy.

It is best that you do not perform a forced unmount so that files are not corrupted.

To get a list of open files on sda2, use the “lsof”’ command as shown in Figure 1.

From Figure 1, you can see there are nine columns for information about the open file:

  • COMMAND – procrss which has the file open
  • PID (Process ID) – the PID of the process which has the file opened
  • USER – the user which has the file open
  • FD (File Descriptor) – indicator used to access files
    • TYPE – type of node for file
    • REG – regular file
    • DIR – directory
    • CHR – Character special file
    • FIFO – First In First Out
    • IP4 – IP4 socket
    • IP6 – IP6 network file
    • AX25 – AX.25 socket
    • INET – Internet domain socket
    • LLA – HP-UX link level access file
    • RTE – AF-Route socket
    • SOCK – unknown domain socket
    • UNIX – UNIX domain socket
    • X.25 – HP-UX x.25 domain socket
    • BLK – Block special file
    • DEL – deleted Linux map file
    • DOOR – VDOOR file
    • KQUEUE – BSD kernel event queue file
    • LINK – Symbolic Link (soft link) file
    • MPB – Multiplexed block file
    • MPC – Multiplexed character file
    • NOFD – /proc/

    /fd/ directory

  • PAS – /proc/as/ file
  • PAXV — /proc/auxv/ file
  • PCRE — /proc/cred/ file
  • PCTL — /proc control file
  • PCUR – current /proc control file
  • PCWD — /proc current working directory
  • PDIR — /proc directory
  • PETY — /proc executable type
  • PFD — /proc file descriptor
  • PFDR — /proc file descriptor directory
  • PFIL — /proc executable file
  • PFPR — /proc FP register set
  • PGD — /proc/pagedata file
  • PGID — /proc group notifier file
  • PIPE — pipes
  • PLC — /proc/lwpctl file
  • PLDR — /proc/lpw directory
  • PLDT — /proc/ldt file
  • PLPI – proc/lpsinfo file
  • PLST — /proc/lsstatus file
  • PLU — /proc/lusage file
  • PLWG — /proc/gwindows file
  • PLWI — /proc/lwpsinfo file
  • PLWS — /proc/lwpstatus file
  • PLWU — /proc/lwpusage file
  • PLWX — /proc/xregs file
  • PMAP — /proc map file
  • PMEM — /proc memory image file
  • PNTF — /proc process notifier file
  • POBJ — /proc/object file
  • PODR — /proc/object directory
  • POLP — /proc light weight process file
  • POPF — /proc PID file
  • POPG — /proc page data file
  • PORT – SYSV named pipe
  • PREG — /proc register file
  • PRMP — /proc/rmap file
  • PRTD — /proc root directory
  • PSGA — /proc/sigact file
  • PSIN — /proc/psinfo file
  • PSTA — /proc status file
  • PSXSEM – POSIX semaphore file
  • PSXSHM – POSIX shared memory file
  • PUSG — /proc/usage file
  • PW — /proc/watch file
  • PXMP — /proc/xmap file
  • SMT – shared memory transport file
  • STSO – stream socket
  • UNM – unnamed type file
  • XNAM – OpenServer Xenix special file of unknown type
  • XSEM – OpenServer Xenix semaphore file
  • XSD – OpenServer Xenix shared data file
  • DEVICE – shows “major,minor” number of device
  • major number of 1 represents IDE
  • major number of 8 represents SCSI
  • SIZE/OFF — file size or offset
  • NODE – file’s iNode number
  • NAME – location of opened file/folder
  • As you can see from Figure 1, the command was run specifically for the ‘sda2’ partition. If the ‘lsof’ command were executed with no location specified, it would check the local filesystem and all mounted filesystems.

    If you are wanting a list of all files opened by a certain process, you can use the ‘-c NAME’ parameter to specify the name of the process, or just a few letters. For example, if I wanted to see all files opened by Libre Office (the command ‘soffice.b’) on all drives I could use the following command:

    lsof -c soffice.b

    I could also specify a specific device, such as sda2 as follows:

    lsof -c soffice.b /dev/sda2/

    If your system is having issues resolving the username, you can use the parameter ‘-l’ to make it show the User ID (UID) instead of the username.

    For network numbers to host name conversion, you can use the parameter ‘-n’ to prevent the conversion. This can make the ‘lsof’ command run a little faster when dealing with network issues.

    For port number to port name conversion, you can use the ‘-P’ parameter to prevent the conversion.

    Once you have found the program which has the open file, you should be able to easily find it and close it. At an extreme, ‘top’ can be used from the Terminal to kill the process, once you know its name. It is also possible to issue the following command to send a ‘sigterm’ signal to the process:

    kill -SIGTERM `lsof -t /dev/sda2/`

    NOTE: SIGTERM (15) can be ignored by some applications, but a SIGKILL (9)
    cannot be ignored. Instead of the name as a parameter, the numbers
    can be used.


    Assume you want to kill all processes created by a user. You would do the
    following:

    kill -9 `lsof -t -u `

    The ‘-u ‘ allows you to specify which user processes you
    are searching for in the open files. The ‘-9’ is a SIGKILL
    parameter.

    NOTE:
    The special symbol (`) is sometimes called a slash quote. It is
    located under the tilde (

    ). It is used to enclose commands which
    need to be executed first. The output is sent to the outer command.

    Источник

    Читайте также:  Ноутбук без предустановленной windows
    Оцените статью