@[toc]
功能
lsof(list open files)是一个列出当前系统打开文件的工具。 lsof 需要访问核心内存和各种文件,需要以 root 用户的身份运行。
语法
语法格式:lsof -i:端口号
示例
lsof -i 显示 tcp,udp 的端口和进程等相关
[root@VM-24-3-centos ~]# lsof -i |more
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 398 root 15u IPv6 151193676 0t0 TCP *:webcache (LISTEN)
java 398 root 27u IPv6 160128834 0t0 TCP VM-24-3-centos:44226->43.250.33.235:https (CLOSE_WAIT)
java 398 root 28u IPv6 160128874 0t0 TCP VM-24-3-centos:44234->43.250.33.235:https (CLOSE_WAIT)
java 398 root 29u IPv6 160128943 0t0 TCP VM-24-3-centos:44248->43.250.33.235:https (CLOSE_WAIT)
java 398 root 30u IPv6 160128959 0t0 TCP VM-24-3-centos:44254->43.250.33.235:https (ESTABLISHED)
java 398 root 31u IPv6 160130075 0t0 TCP VM-24-3-centos:44280->43.250.33.235:https (ESTABLISHED)
java 398 root 32u IPv6 160130186 0t0 TCP VM-24-3-centos:44296->43.250.33.235:https (ESTABLISHED)
java 398 root 33u IPv6 160130475 0t0 TCP VM-24-3-centos:44318->43.250.33.235:https (ESTABLISHED)
java 398 root 34u IPv6 160131452 0t0 TCP VM-24-3-centos:44356->43.250.33.235:https (ESTABLISHED)
java 398 root 45u IPv6 160128687 0t0 TCP VM-24-3-centos:44204->43.250.33.235:https (CLOSE_WAIT)
java 555 root 19u IPv6 159554061 0t0 TCP VM-24-3-centos:55346->43.250.33.235:https (CLOSE_WAIT)
java 555 root 21u IPv6 159675287 0t0 TCP VM-24-3-centos:38397->43.250.33.235:https (CLOSE_WAIT)
java 555 root 22u IPv6 160130806 0t0 TCP VM-24-3-centos:44334->43.250.33.235:https (ESTABLISHED)
查看服务器 80 端口的占用情况
[root@VM-24-3-centos ~]# lsof -i:80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 18454 root 7u IPv4 111507996 0t0 TCP *:http (LISTEN)
nginx 25798 www 7u IPv4 111507996 0t0 TCP *:http (LISTEN)
nginx 25799 www 7u IPv4 111507996 0t0 TCP *:http (LISTEN)
[root@VM-24-3-centos ~]#
- COMMAND:进程的名称
- PID进程标识符
- USER:进程所有者
- FD:文件描述符,应用程序通过文件描述符识别该文件,如cwd、txt等
- TYPE:文件类型,如DIR、REG等
- DEVICE:指定磁盘的名称
- SIZE:文件的大小
- NODE:索引节点(文件在磁盘上的标识)
- NAME:打开文件的确切名称
使用 -p 查看指定进程打开的文件
[root@VM-24-3-centos ~]# lsof -p 398
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 398 root cwd DIR 253,1 4096 793920 /root/xxx
java 398 root rtd DIR 253,1 4096 2 /
java 398 root txt REG 253,1 8984 794871 /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.352.b08-2.el7_9.x86_64/jre/bin/java
java 398 root mem REG 253,1 109976 21146 /usr/lib64/libresolv-2.17.so
java 398 root mem REG 253,1 31344 3924 /usr/lib64/libnss_dns-2.17.so
java 398 root mem REG 253,1 4004256 794934 /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.352.b08-2.el7_9.x86_64/jre/lib/ext/cldrdata.jar
更多命令
lsof -i
: 查看IPv4/6文件lsof -i:8080
:查看8080端口占用lsof -i4
: 查看IPv4文件lsof -i6
: 查看IPv6文件lsof -i TCP:80
查看TCP协议80端口占用情况lsof -c lsof
查看lsof命令使用的所有文件lsof -p 1234
:列出进程号为1234的进程所打开的文件lsof -g gid
:显示归属gid的进程情况lsof +d /usr/local/
:显示目录下被进程开启的文件lsof +D /usr/local/
:同上,但是会搜索目录下的目录,时间较长lsof -d 4
:显示使用fd为4的进程lsof -i -U
:显示所有打开的端口和UNIX domain文件