原理:在Linux系統的/proc 分區下儲存著進程的目錄和名字,包含fd(檔案描述符)和其下的子目錄(進程開啟檔案的連結),那麼如果刪除了一個檔案,還存在一個 inode的引用:/proc/進程號/fd/檔案描述符。我們只要知道當前開啟檔案的進程pid和檔案描述符fd就能利用lsof工具列出進程開啟的檔案。
一、將 ls 的手冊過濾掉主要控制符後重新導向到檔案ls.txt 中,並用more查看,CTRL + Z 暫停查看操作
1: [root@localhost script]# man ls |col -b > ls.txt
2: [root@localhost script]# more ls.txt
3: LS(1) User Commands LS(1)
4:
1: [1]+ Stopped more ls.txt
2: [root@localhost script]#
3: [root@localhost script]# jobs
4: [1]+ Stopped more ls.txt
5:
二、假設誤刪檔案 ls.txt
1: [root@localhost script]# rm ls.txt
2: rm:是否刪除 一般檔案 “ls.txt”? y
三、利用lsof找到進程6511、並拷貝恢複,只能在這個檔案被使用或調用的情況下有效
3: [root@localhost script]# lsof |grep ls.txt
4: more 6511 root 3r REG 253,0 7300 1083699 /opt/script/ls.txt (deleted)
5:
1: [root@localhost script]# ls -l /proc/6511/fd/
2: 0 1 2 3
3: [root@localhost script]# ls -l /proc/6511/fd/3
4: lr-x------ 1 root root 64 10-30 21:21 /proc/6511/fd/3 -> /opt/script/ls.txt (deleted)
5:
1: cp /proc/6511/fd/3 ls.txt.saved