拓展知识:linux使用lsof恢复误删除的nginx日志
图解流程:

-
确保当前nginx进程运行中
```bash [root@server ~]#ps -ef | grep nginx root 40538 1 0 22:06 ? 00:00:00 nginx: master process /usr/sbin/nginx nginx 40539 40538 0 22:06 ? 00:00:00 nginx: worker process nginx 40540 40538 0 22:06 ? 00:00:00 nginx: worker process ``` -
删除日志文件,rm -f /var/log/nginx/access.log
```bash [root@server ~]#rm /var/log/nginx/access.log rm: remove regular file ‘/var/log/nginx/access.log’? y ``` -
使用lsof查看系统关于access.log的文件进程
```bash [root@server ~]#lsof | grep access.log nginx 40538 root 5w REG 8,2 17887 1988160 /var/log/nginx/access.log (deleted) nginx 40539 nginx 5w REG 8,2 17887 1988160 /var/log/nginx/access.log (deleted) nginx 40540 nginx 5w REG 8,2 17887 1988160 /var/log/nginx/access.log (deleted) ``` -
根据进程id查找已删除文件
```bash [root@server ~]#ll /proc/40538/fd/ total 0 lrwx------ 1 root root 64 Mar 23 22:07 0 -> /dev/null l-wx------ 1 root root 64 Mar 23 22:07 2 -> /var/log/nginx/error.log l-wx------ 1 root root 64 Mar 23 22:07 4 -> /var/log/nginx/error.log l-wx------ 1 root root 64 Mar 23 22:07 5 -> /var/log/nginx/access.log (deleted) ```说明: proc目录中存放进程打开的文件,access.log虽然在磁盘中删除了,由于进程正在使用此文件,所有此文件在内存中还有一份,我们可以将内存中的文件复制到磁盘中,以此达到恢复文件的目的
-
恢复已删除文件
```bash [root@server ~]#cp /proc/40538/fd/5 /var/log/nginx/access.log ``` -
重新加载nginx服务,访问网站测试文件是否恢复正常
```bash [root@server ~]#systemctl reload nginx.service [root@server ~]#tail -f /var/log/nginx/access.log 10.0.0.1 - - [23/Mar/2022:22:18:36 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.46" "-" ``` ---![image-20220323220807837]()
本文来自博客园,作者:echo勇往直前,转载请注明原文链接:https://www.cnblogs.com/wangrengang/p/16047403.html


浙公网安备 33010602011771号