拓展知識-linux使用lsof恢復誤刪除的nginx日誌
阿新 • • 發佈:2022-03-23
圖解流程:
-
確保當前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" "-" ``` ---