Lan Yiyun: Linux hijacks the rm command to achieve safe deletion

In Linux systems, rmsafe deletion can be achieved by hijacking (or overwriting) commands to prevent accidental deletion of important files. By hijacking  rma command, it can be replaced with a custom script or command, adding additional security confirmation steps, such as asking the user to confirm deletion.

Here's a simple way to achieve secure deletion:

  1. Create a custom  rmscript:
    First, create a  rmscript file called , save it in a secure directory (for example  /usr/local/bin/) and give it executable permissions.
sudo touch /usr/local/bin/rm
sudo chmod +x /usr/local/bin/rm
  1. Edit  rmthe script:
    Open the script with a text editor  rmand add the following:
#!/bin/bash

# 自定义rm命令脚本

# 确认提示信息
echo "您正在执行rm命令,是否确认删除?[Y/N]"
read response

# 判断用户输入
if [ "$response" == "Y" ] || [ "$response" == "y" ]; then
    # 用户确认删除,执行真正的rm命令
    /bin/rm "$@"
else
    # 用户取消删除
    echo "已取消删除操作。"
fi
  1. Set system  PATHenvironment variables:
    In order to ensure that the system uses custom  rmscripts instead of default  rmcommands, you need to add the directory containing the custom scripts to the system  PATHenvironment variables. In this way, when the command is executed  rm, the system will first find and use the custom script.
export PATH="/usr/local/bin:$PATH"

To make this setting permanent, add the above command to  the ~/.bashrcor  ~/.bash_profilefile.

Now, when you execute the command in the terminal  rm, a confirmation prompt will pop up asking you to confirm the deletion. If you type  Yor  yand press enter, the real  rmcommand is executed to delete. If you enter any other characters (including the Enter key), the delete operation will be canceled.

Please note that the hijack  rmcommand needs to be used with caution, ensuring that removal operations are only performed when necessary. At the same time, it is recommended to back up important files to prevent data loss caused by misoperation.

Guess you like

Origin blog.csdn.net/tiansyun/article/details/133323941