简介
lsof全名list opened files ,yum install lsof即可。linux环境中,任何事物都是文件,设备是文件,目录是文件,甚至sockets也是文件。
lsof命令基本使用
- lsof 所有的options都是一些过滤条件
- lsof -a 表示and连接操作符,制定所有条件都满足,默认or, 如
lsof -a -u root -d txt
- lsof -c string 显示COMMAND列中包含指定字符的进程所有打开的文件,常用于查找应用程序打开的文件的名称和数目,如
lsof -c mysqld
- lsof -u username 显示所属user进程打开的文件
- lsof +d /DIR/ 显示目录下被进程打开的文件
- lsof +D /DIR/ 同上,但是会搜索目录下的所有目录,时间相对较长
- lsof -i 根据IPv46过滤,格式:
[proto][@host|addr][:svc_list|port_list]
,例如lsof -i TCP@0.0.0.0:3306
,但是这里的协议,host,port三者不一定全部限定,例如常见的根据端口找进程lsof -i :3306
或lsof -i:3306
不要空格
使用lsof恢复删除文件
这种恢复方式是有条件的,期望这个文件被删除前在被某种程序使用吧
模拟一个进程打开/ect/my.cnf,这里vim /etc/my.cnf
即可,这时可见其实打开的是一个临时副本
[root@node-126 ~]# lsof |grep my.cnf
vim 20844 root 4u REG 253,0 12288 33554509 /etc/.my.cnf.swp
误删本体rm -rf /etc/my.cnf
后便可以根据临时文件恢复。注意该文件是二进制,需要使用strings
命令来打开,除前几行既是要恢复的原文件内容。
[root@node-126 etc]# strings /etc/.my.cnf.swp
b0VIM 7.4
root
node-126
/etc/my.cnf
3210
#"!
pid-file=/var/run/mysqld/mysqld.pid
log-error=/var/log/mysqld.log
symbolic-links=0
# Disabling symbolic-links is recommended to prevent assorted security risks
socket=/var/lib/mysql/mysql.sock
datadir=/var/lib/mysql
# read_rnd_buffer_size = 2M
# sort_buffer_size = 2M
# join_buffer_size = 128M
# Adjust sizes as needed, experiment to find the optimal values.
# The server defaults are faster for transactions and fast SELECTs.
# Remove leading # to set options mainly useful for reporting servers.
# log_bin
# changes to the binary log between backups.
# Remove leading # to turn on a very important data integrity option: logging
# innodb_buffer_pool_size = 128M
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# Remove leading # and set to the amount of RAM for the most important data
[mysqld]
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html
# For advice on how to change settings please see
也可以根据FD来恢复strings /proc/20844/fd/4
, 20844为打开该文件的PID,4为FD
[root@node-126 ~]# lsof |grep my.cnf
vim 20844 root 4u REG 253,0 12288 33554509 /etc/.my.cnf.swp