linux下有很多实用的命令(tool), lsof就是其中一个,其作用为查看系统打开的文件。
其常用场景整理如下:
1、看下某个(rsyslogd)进程打开了哪些文件
1) 查看rsyslogd的进程号
[root@localhost ~]#ps -elf | grep rsyslogd
5 S root 1487 1 0 80 0 - 62289 poll_s 07:40 ? 00:00:00 /sbin/rsyslogd -i /var/run/syslogd.pid -c 5
2) 使用lsof查看 lsof -p pid #其中pid为rsyslogd的pid
[root@localhost pthread_test]# lsof -p 1487
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
rsyslogd 1487 root cwd DIR 253,0 4096 2 /
rsyslogd 1487 root rtd DIR 253,0 4096 2 /
rsyslogd 1487 root txt REG 253,0 391360 6614 /sbin/rsyslogd
rsyslogd 1487 root mem REG 253,0 27232 42881 /lib64/rsyslog/imklog.so
rsyslogd 1487 root mem REG 253,0 339960 42887 /lib64/rsyslog/imuxsock.so
rsyslogd 1487 root mem REG 253,0 26984 42888 /lib64/rsyslog/lmnet.so
rsyslogd 1487 root mem REG 253,0 1928936 68701 /lib64/libc-2.12.so
rsyslogd 1487 root mem REG 253,0 93320 70621 /lib64/libgcc_s-4.4.7-20120601.so.1
rsyslogd 1487 root mem REG 253,0 47168 70560 /lib64/librt-2.12.so
rsyslogd 1487 root mem REG 253,0 22536 70556 /lib64/libdl-2.12.so
rsyslogd 1487 root mem REG 253,0 145936 70547 /lib64/libpthread-2.12.so
rsyslogd 1487 root mem REG 253,0 91096 70552 /lib64/libz.so.1.2.3
rsyslogd 1487 root mem REG 253,0 157072 68687 /lib64/ld-2.12.so
rsyslogd 1487 root 0u unix 0xffff8800369cf080 0t0 13462 /dev/log
rsyslogd 1487 root 1w REG 253,0 30523 36300 /var/log/messages
rsyslogd 1487 root 2w REG 253,0 5262 36125 /var/log/cron
rsyslogd 1487 root 3r REG 0,3 0 4026532040 /proc/kmsg
rsyslogd 1487 root 4w REG 253,0 592 36127 /var/log/maillog
从上面可以看到rsyslogd 进程打开的文件列表(包含程序bin文件、动态库、读文件及目的文件)
2、 查看某个文件被哪些进程打开:
[root@localhost ~]# lsof /dev/log
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
rsyslogd 1487 root 0u unix 0xffff8800369cf080 0t0 13462 /dev/log
3、 查看端口被哪个进程占用
[root@localhost ~]#netstat -an |grep 6379
tcp4 0 0 *.6379 *.* LISTEN
tcp6 0 0 *.6379 *.* LISTEN
[root@localhost ~]#lsof -i :6379
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
redis-ser 911 root 4u IPv6 0x69a37df87bd085e1 0t0 TCP *:6379 (LISTEN)
redis-ser 911 root 5u IPv4 0x69a37df8823a03c1 0t0 TCP *:6379 (LISTEN)
从上面的结果可以看到6379端口被redis-server使用
4、查看某个用户打开的文件列表
lost -u root
5、 查看tcp和udp的网络连接信息
[root@localhost ~]#lsof -i tcp
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
Google 274 root 15u IPv4 0x69a37df8825287a1 0t0 TCP 192.168.1.100:50389->203.208.41.41:https (ESTABLISHED)