![282bd154524bd05b56ebf64ad99d6159.png](https://i-blog.csdnimg.cn/blog_migrate/01499bc7a9aba910319b828bcad06d17.jpeg)
lsof是List Open Files的缩写。顾名思义,它用来查看系统中进程打开了哪些文件;因为Linux几乎所有的设备都可以看成是文件,所以lsof经常也可以用来查看管道,sockets的使用状态。
查看当前所有的活跃连接
# lsof -iCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMErpcbind 1203 rpc 6u IPv4 11326 0t0 UDP *:sunrpcrpcbind 1203 rpc 7u IPv4 11330 0t0 UDP *:954rpcbind 1203 rpc 11u IPv6 11336 0t0 TCP *:sunrpc (LISTEN)avahi-dae 1241 avahi 13u IPv4 11579 0t0 UDP *:mdnsavahi-dae 1241 avahi 14u IPv4 11580 0t0 UDP *:58600rpc.statd 1277 rpcuser 11u IPv6 11862 0t0 TCP *:56428 (LISTEN)cupsd 1346 root 6u IPv6 12112 0t0 TCP localhost:ipp (LISTEN)cupsd 1346 root 7u IPv4 12113 0t0 TCP localhost:ipp (LISTEN)sshd 1471 root 3u IPv4 12683 0t0 TCP *:ssh (LISTEN)...
查看指定进程打开的文件
# lsof -p `pidof systemd`COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEsystemd 1 root cwd DIR 8,2 4096 128 /systemd 1 root rtd DIR 8,2 4096 128 /systemd 1 root txt REG 8,2 1612152 100958350 /usr/lib/systemd/systemdsystemd 1 root mem REG 8,2 20112 67195580 /usr/lib64/libuuid.so.1.3.0systemd 1 root mem REG 8,2 261488 67202929 /usr/lib64/libblkid.so.1.1.0systemd 1 root mem REG 8,2 90664 67202184 /usr/lib64/libz.so.1.2.7...
查看指定端口被哪个进程占用
# lsof -i :22COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEsshd 1017 root 3u IPv4 19044 0t0 TCP *:ssh (LISTEN)sshd 1017 root 4u IPv6 19053 0t0 TCP *:ssh (LISTEN)sshd 1542 root 3u IPv4 28685 0t0 TCP localhost.localdomain:ssh->192.168.1.102:61167 (ESTABLISHED)
过滤指定的连接状态
# lsof -i :22 -s TCP:LISTENCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEsshd 1017 root 3u IPv4 19044 0t0 TCP *:ssh (LISTEN)sshd 1017 root 4u IPv6 19053 0t0 TCP *:ssh (LISTEN)
支持的TCP状态包括: CLOSED, IDLE, BOUND, LISTEN, ESTABLISHED, SYN_SENT, SYN_RCDV, ESTABLISHED, CLOSE_WAIT, FIN_WAIT1, CLOSING, LAST_ACK, FIN_WAIT_2, and TIME_WAIT。
支持的UDP状态包括: Unbound和Idle。
如何防止第一列命令行被截断
如果命令的文件名超过9个字符,lsof会默认截断这个命令:
# lsof |grep kworkerkworker/0 5 root cwd DIR 8,2 4096 128 /kworker/0 5 root rtd DIR 8,2 4096 128 /kworker/0 5 root txt unknown /proc/5/exe
可以使用+c 0防止命令被截断:
# lsof +c 0|grep kworkerkworker/0:0H 5 root cwd DIR 8,2 4096 128 /kworker/0:0H 5 root rtd DIR 8,2 4096 128 /kworker/0:0H 5 root txt unknown