網上流傳的安全的rm,幾乎都是提供一個rm的"垃圾"回收站,在服務器環境上來講,這實非良方。git
我想,提供一個安全的rm去保護一些重要的文件或目錄不被刪除,避免出現重要數據誤刪的悲劇,或許纔是更佳方案。github
我寫了一個腳本:https://github.com/malongshuai/rm_is_safe ,源碼和用法本文後面已經提供了,不過各位願意捧場的能夠去github上點個star。shell
rm_is_safe
會建立一個名爲/bin/rm
的shell腳本,同時會備份原生的/bin/rm爲/bin/rm.bak。因此,原來如何使用rm,如今也以同樣的方式使用rm,沒有任何區別。安全
爲了區分原生rm和假裝後的安全的rm,下面將假裝的rm命令稱爲rm_is_safe
。bash
rm_is_safe
會自動檢查rm被調用時傳遞的參數,若是參數中包含了重要文件,可能意味着這是一次危險的rm操做,rm_is_safe
會直接忽略本次rm。至於哪些屬於重要文件,由你本身來決定。服務器
rm_is_safe
對全部用戶都有效,包括目前已存在的用戶和將來新建立的用戶。app
根目錄/
以及根目錄下的子目錄、子文件老是自動被保護的函數
你能夠在/etc/security/rm_fileignore
中定義你本身以爲重要的文件,每行定義一個被保護的文件路徑。例如:code
/home/junmajinlong /home/junmajinlong/apps
如今,該文件中定義的兩個文件都被保護起來了,它們是安全的,不會被rm刪除。遞歸
注意事項:
/
以及根目錄下的子目錄是自動被保護的,不用手動將它們添加到/etc/security/rm_fileignore中rm_is_safe
會自動處理。因此,'/home/junmajinlong'和'/home///junmajinlong/////'都是有效路徑/home/*
是無效的1.執行本文後面提供的Shell腳本:
$ sudo bash rm_is_safe.sh
執行完成後,你的rm命令就變成了安全的rm了。
2.若是確實想要刪除被保護的文件,好比你明確知道/data是能夠刪除的,那麼你可使用原生的rm命令,即/bin/rm.bak來刪除。
$ rm.bak /path/to/file
3.若是你想要卸載rm_is_safe
,執行函數uninstall_rm_is_safe
便可:
# 若是找不到該函數,則先exec bash,再執行便可 $ uninstall_rm_is_safe
卸載完成後,/bin/rm
就變回原生的rm命令了。
腳本以下,假設其文件名爲rm_is_safe.sh
:
#!/bin/bash ############################### # Author: www.junmajinlong.com ############################### # generate /bin/rm # 1.create file: /etc/security/rm_fileignore # 2.backup /bin/rm to /bin/rm.bak function rm_is_safe(){ [ -f /etc/security/rm_fileignore ] || touch /etc/security/rm_fileignore if [ ! -f /bin/rm.bak ];then file /bin/rm | grep -q ELF && /bin/cp -f /bin/rm /bin/rm.bak fi cat >/bin/rm<<'eof' #!/bin/bash args=$(echo "$*" | tr -s '/' | tr -d "\042\047" ) safe_files=$(find / -maxdepth 1 | tr '\n' '|')\ $(cat /etc/security/rm_fileignore | tr '\n' '|') echo "$args" | grep -qP "(?:${safe_files%|})(?:/?(?=\s|$))" if [ $? -eq 0 ];then echo -e "'\e[1;5;33mrm $args\e[0m' is not allowed,Exit..." exit 1 fi /bin/rm.bak "$@" eof chmod +x /bin/rm } # for uninstall rm_is_safe # function `uninstall_rm_safe` used for uninstall function un_rm(){ # make efforts for all user if [ ! -f /etc/profile.d/rm_is_safe.sh ];then shopt -s nullglob for uh in /home/* /root /etc/skel;do shopt -u nullglob cat >>$uh/.bashrc<<'eof' # for rm_is_safe: [ -f /etc/profile.d/rm_is_safe.sh ] && source /etc/profile.d/rm_is_safe.sh eof done fi cat >/etc/profile.d/rm_is_safe.sh<<'eof' function uninstall_rm_is_safe(){ unset uninstall_rm_is_safe /bin/unlink /etc/security/rm_fileignore /bin/cp -f /bin/rm.bak /bin/rm /bin/unlink /etc/profile.d/rm_is_safe.sh shopt -s nullglob for uh in /home/* /root /etc/skel;do shopt -u nullglob sed -ri '\%# for rm_is_safe%,\%/etc/profile.d/rm_is_safe.sh%d' $uh/.bashrc done } export -f uninstall_rm_is_safe eof } rm_is_safe un_rm