Linux lsof命令的使用示例

Linux命令中,lsof代表 LiStOpenFiles,用于查看所有被打开的文件,同时显示打开文件相对应的进程。
Linux/Unix把一切都看做文件(pipes,sockets,directories,devices etc),使用这个命令,可以轻易查看文件被进程占用情况。

1、列出所有打开文件

lsof

输出:

COMMAND    PID      USER   FD      TYPE     DEVICE  SIZE/OFF       NODE NAME
init         1      root  cwd      DIR      253,0      4096          2 /
init         1      root   3r     FIFO        0,8       0t0       8449 pipe
init         1      root   5r      DIR       0,10         0          1 inotify
init         1      root   7u     unix 0xc1513880       0t0       8450 socket

完整列表会很长,每一行列出了相应的值,下面重点看下 FD & TYPE的值。

FD -文件描述 (File descriptor),可能的值:

  • cwd current working directory
  • rtd root directory
  • txt program text (code and data)
  • mem memory-mapped file

同样在FD列中,数字1u是实际的文件描述符,后跟u、r、w,其模式如下:

  • r for read access.
  • w for write access.
  • u for read and write access.

TYPE – 文件识别类型(identification)

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

2、列出指定用户打开文件

lsof -u root

3、列出指定端口

lsof -i TCP:22
lsof -i:22
lsof -i TCP:1-1024 #端口号为一范围

4、列出 IPv4 & IPv6 网络打开文件

lsof -i 4/6

5、列出非某个用户打开文件(^)

lsof -i -u^root

6、列出所有网络连接,监听与已建立

lsof -i # i是 IPv[46]的首字母

7、列出指定PID

lsof -p 1

8、杀死某个用户的所有进程

kill -9 `lsof -t -u tecmint`

参考

10 lsof Command Examples in Linux

posted @ 2021-03-13 09:50  皎然CEO  阅读(144)  评论(0编辑  收藏  举报