rm -rf

rm -rf

最近做大死碰上了Linux系统最致命的指令rm -rf /, 服务器资料全被删。

好在还没执行任何写操作,数据应该都还在,做此笔记记录下恢复过程。

undelete files

reference: linux下rm -r误删NTFS文件恢复方法

Use ntfs-3g_ntfsprogs to undelete files.

$ ntfsundelete /dev/sdb1 > files.txt                             # list all recoverable files
$ ntfsundelete /dev/sdb1 -u -i <inode> -o <tgtname> -d <tgt/dir> # recover the specific file

parse files

Not all files recorvered by ntfsundelete has a filename.
So undelete all files as unknown and use file util to recognize the recorved files’ type, then rename with suffixes.

parseFiles.shparseFiles.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
for file in ./*
do
# get file type
t=$(file $file)
t=${t#*\ }
t=${t%%,*}
echo $t
# add supported file type and the actions here
case $t in
"Zip archive data")
mv -v $file ../zips/
sh /utils/parseZip.sh ../zips/$file
;;
"gzip compressed data")
mv -v $file ../gzips/${file}.tar.gz
;;
"ASCII text")
mv -v $file ../texts/${file}.txt
;;
"C source")
mv -v $file ../cs/${file}.c
;;
esac
done

Cause the new office files are stored as zip archive, use parseZip.sh to recognize them and reset their suffixes.

parseZip.hparseZip.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
suffix=""
get_suffixes () {
unzip -l $1 > /dev/null 2>&1
if [ "$?" -ne 0 ]; then
suffix="zip-corrupt"
elif [ ! -z "$(unzip -l $1 | grep word)" ]; then
suffix="docx" # word
elif [ ! -z "$(unzip -l $1 | grep xl)" ]; then
suffix="xlsx" # excel
elif [ ! -z "$(unzip -l $1 | grep ppt)" ]; then
suffix="pptx" # ppt
elif [ ! -z "$(unzip -l $1 | grep visio)" ]; then
suffix="vsdx" # visio
else
suffix="zip"
fi
}
for file in ./*
do
get_suffixes $file
filename=${file%\.*}.$suffix
mv $1 $filename
done

rename files

Python has modules that can r/w with files, such as python-docx with docx, pypdf2 with pdf, rarfile with rar ans so on.
So we use python to analyse the target file and rename the files according to its title or content.

RenameFiles.pyRenameFiles.py
1
2
3
4
5
6
7
8
if __name__ == "__main__":
for file_ in os.listdir('.'):
if os.path.isfile(file_):
print "@--->%s" % file_
f = RenameFiles(file_)
f.rename()
print "\nDone!"