lsof linux

lsof  list open files

Linux一切皆文件,通过文件不仅可以访问常规数据,还可以访问网络连接(套接字)和硬件,该文件描述符为应用程序与os之间提供了接口.lsof需访问各种特权文件,故需root运行

 

 

 COMMAND contains  the  first nine characters of the name of the UNIX command associated with the process. 默认只显示前9个字符

 PID is the Process IDentification number of the process.

 TID  is the task (thread) IDentification number, if task (thread) reporting is supported by the dialect and a task (thread) is being listed.

 FD is the File Descriptor number of the file or:

  1. cwd  current working directory
  2. mem memory mapped file
  3. rtd root directory
  4. txt program text (code and data)

 FD is followed by one of these characters, describing the mode under which the file is open:

  1. r for read access
  2. w for write access
  3. u for read and write access
  4. space if mode unknow and no lock

 TYPE is the type of the node associated with the file

  1. IPv4 IPv4 socket
  2. IPv6 an open IPv6 network file - even if its address is IPv4, mapped in an IPv6 address
  3. unix UNIX domain socket
  4. DIR directory
  5. FIFO FIFO special file
  6. DEL a linux map file that has been deleted
  7. CHR a charater special file 字符设备文件
  8. BLK a block special file 块设备文件
  9. SOCK  a socket of unknown domain
  10. REG regular file 

 

  lsof常用用法

  1. -u 后面可跟uid 用户名 前面加^表示取反
    lsof -u polkitd
    lsof -u ^polkitd
    lsof -u 81

     

     lsof -u ^81

  2. lsof -i 用来查看套接字文件
    lsof -i 所有套接字的连接
    lsof -i tcp
    lsof -i udp
    lsof -i :80
    lsof -i tcp:80
    lsof -U Unix socket Unix域套接字

     

     有个特殊用法可以显示到某个远程主机特点端口的连接


     

  3. -n 不做反解
  4. -r n repeat every n seconds

     

     

  5. -d select by FD set
    lsof -d 22

     


    lsof -d 24-25

     

     lsof -d 30,33



  6. -g select by gid
    lsof -g 0 查看gid为0的所有组内成员打开的文件
    lsof -g ^0 exclude gid 0
  7. lsof -N
    select NFS files



  8. lsof -i -a -u root    列出所有root用户的sockets文件
    支持-a做and逻辑运算



  9. lsof -p select by pid

     

  10. lsof -u select by uid


    lsof -u ^postfix

     

  11. lsof -c select by command

    列出以post开头程序打开的文件
    lsof -c ^post

  12. lsof +D /path/to/dir
    递归列出打开对应dir下所有文件的进程,必须是目录

     

lsof 可以用来恢复特定情况下被删除的文件,当进程打开了某个文件,在/proc/PID/fd中即建立相应的文件描述符与此文件关联,在文件系统中将此文件删除,删除了文件系统目录索引,但是文件仍然存在于磁盘,进程并不知道文件被删除,仍然可以向对应的fd读取或写入,但是此文件在fs中已经无法找到,/proc挂载的是内存中所映射的一块区域,所以fd关联的文件其实位于内存中,当对fd进行读取或写入,是与内存进行交互,lsof即是访问/proc目录的文件描述符抽取信息.

当系统的某个文件被意外删除,如果还有进程在访问此文件,那就可以利用对应的fd恢复相应内容,

 

 

 

 上面为对应的操作流程

 

posted @ 2020-06-02 22:41  ascertain  阅读(181)  评论(0编辑  收藏  举报