1.1. lsof 使用
1.1.1. lsof - list open files //列出当前系统打开文件
lsof 4.89
latest revision: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/
latest FAQ: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/FAQ
latest man page: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/lsof_man
usage: [-?abhlnNoOPRtUvV] [+|-c c] [+|-d s] [+D D] [+|-f[cgG]]
[-F [f]] [-g [s]] [-i [i]] [+|-L [l]] [+|-M] [-o [o]] [-p s]
[+|-r [t]] [-s [p:s]] [-S [t]] [-T [t]] [-u s] [+|-w] [-x [fl]] [--] [names]
Defaults in parentheses; comma-separated set (s) items; dash-separated ranges.
-?|-h list help -a AND selections (OR) -b avoid kernel blocks
-c c cmd c ^c /c/[bix] +c w COMMAND width (9) +d s dir s files
-d s select by FD set +D D dir D tree *SLOW?* -i select IPv[46] files
-l list UID numbers -n no host names -N select NFS files
-o list file offset -O no overhead *RISKY* -P no port names
-R list paRent PID -s list file size -t terse listing
-T disable TCP/TPI info -U select Unix socket -v list version info
-V verbose search +|-w Warnings (+) -- end option scan
+f|-f +filesystem or -file names +|-f[cgG] Ct flaGs
-F [f] select fields; -F? for help
+|-L [l] list (+) suppress (-) link counts < l (0 = all; default = 0)
+|-M portMap registration (-) -o o o 0t offset digits (8)
-p s exclude(^)|select PIDs -S [t] t second stat timeout (15)
-T fqs TCP/TPI Fl,Q,St (s) info
-g [s] exclude(^)|select and print process group IDs
-i i select by IPv[46] address: [46][proto][@host|addr][:svc_list|port_list]
+|-r [t[m<fmt>]] repeat every t seconds (15); + until no files, - forever.
An optional suffix to t is m<fmt>; m must separate t from <fmt> and
<fmt> is an strftime(3) format for the marker line.
-s p:s exclude(^)|select protocol (p = TCP|UDP) states by name(s).
-u s exclude(^)|select login|UID set s
-x [fl] cross over +d|+D File systems or symbolic Links
names select named files or files on named file systems
Anyone can list all files; /dev warnings disabled; kernel ID check disabled.
- 默认 : 没有选项,lsof列出活跃进程的所有打开文件
- 组合 : 可以将选项组合到一起,如-abc,但要当心哪些选项需要参数
- a : 结果进行“与”运算(而不是“或”)
- l : 在输出显示用户ID而不是用户名
- h : 获得帮助
- t : 仅获取进程ID
- U : 获取UNIX套接口地址
- F : 格式化输出结果,用于其它命令。可以通过多种方式格式化,如-F pcfn(用于进程id、命令名、文件描述符、文件名,并以空终止)
1.2. 获取网络信息
- 使用-i仅获取IPv4 OR IPv6流量
lsof -i 4 lsof -i 6
- 仅显示TCP连接(同理可获得UDP连接)
lsof -i TCP #or UDP
- 使用-i:port来显示与指定端口相关的网络信息
lsof -i:8080
- 使用@host来显示指定到指定主机的连接
lsof -i @127.0.0.1
- 使用@host:port显示基于主机与端口的连接
lsof -i @127.0.0.1:3306
- 找出正等候连接的端口
lsof -i -s TCP:LISTEN # lsof -i | grep -i LISTEN
- 找出已建立的连接
lsof -i -s TCP:ESTABLISHED # lsof -i | grep -i ESTABLISHED
- 范围端口查询
lsof -i @127.0.0.1:2150=2180
- lsof -n 不将IP转换为hostname
- lsof -g gid 显示归属gid的进程情况
1.3. 命令和进程
使用-p查看指定进程ID已打开的内容
lsof -p 24333
使用-c查看 [指定的命令] 正在使用的文件和网络连接
lsof -c watch
-t选项只返回PID
lsof -c watch -t