Linux防止文件和目录被意外删除或修改

您所在的位置:网站首页 怎么防止误删文件 Linux防止文件和目录被意外删除或修改

Linux防止文件和目录被意外删除或修改

2023-07-03 09:14| 来源: 网络整理| 查看: 265

为了防止在 Linux 系统中意外删除一些重要文件或目录,除了必要的备份之外,还有一个好方法,就是使用:

chattr(Change Attribute)命令

在类 Unix 等发行版中,该命令能够有效防止文件和目录被意外的删除或修改。file 文件在 Linux 中被描述为一个数据结构,chattr 命令在大多数现代 Linux 操作系统中是可用的,可以修改file属性,一旦定义文件的隐藏属性,那么该文件的拥有者和 root 用户也无权操作该文件,只能解除文件的隐藏属性。

命令语法

chattr [operator] [switch] [file]

chattr 具有如下操作符:

操作符 +,追加指定属性到文件已存在属性中操作符 -, 删除指定属性操作符 =,直接设置文件属性为指定属性

chattr 常用属性指令如下:

a - 只能向文件中添加数据A - 不更新文件或目录的最后访问时间i - 文件或目录不可改变

使用 lsattr 命令检查文件已有属性: -d:如果目标是目录,只会列出目录本身的隐藏属性,而不会列出所含文件或子目录的隐藏属性信息 -R:作用于目录时,会显示所有的子目录和文件的隐藏信息

codedancing@Ubuntu:~$ lsattr -d ./src -----a--------e--- ./src codedancing@Ubuntu:~$ lsattr ./src --------------e--- ./src/Python-3.7.6 --------------e--- ./src/test.txt --------------e--- ./src/redis-5.0.7

使用 i 属性:

1. 操作文件 如果对文件设置i 属性,那么不允许对文件进行改名、移动和删除,也不能添加和修改数据

# 当前目录创建一个file.txt文件 touch file.txt sudo chattr +i file.txt lsattr ./file.txt ----i---------e--- ./file.txt

尝试删除文件:

rm -f ./file.txt rm: cannot remove './file.txt': Operation not permitted

尝试修改文件:

echo 'Hello World!' > file.txt bash: ./file.txt: Operation not permitted

尝试移动文件:

mv ./file.txt ./fileDir mv: cannot move './file.txt' to './fileDir/file.txt': Operation not permitted

2. 操作文件夹 如果对目录设置 i 属性,那么只能修改目录下文件中的数据,但不允许建立、移动和删除文件

mkdir ./fileDir && touch ./fileDir/file.txt

现在,让目录及其内容都不可改变(使用 -R):

sudo chattr +i -R ./fileDir

尝试删除文件夹

rm -rf ./fileDir rm: cannot remove './fileDir/file.txt': Operation not permitted

当然也不能修改、删除该文件夹中的内容。

使用 a 属性:

如果一个文件设置了 a 属性,那么只能在文件中増加数据,但是不能修改和删除数据,不能移动该文件

sudo chattr +a ./file.txt lsattr ./file.txt -----a--------e--- ./file.txt echo "asdfas" >> ./file.txt # OK echo "sdfsd"> ./file.txt bash: ./file.txt: Operation not permitted

如果一个文件夹设置了 a 属性,那么只允许在目录中建立和修改文件,但是不允许删除、移动文件

sudo chattr +a ./fileDir

-----------------------------------------------------------------------------------------------

注意

BUGS AND LIMITATIONS The ‘c’, ‘s’, and ‘u’ attributes are not honored by the ext2, ext3, and ext4 filesystems as implemented in the current mainline Linux kernels. The ‘j’ option is only useful for ext3 and ext4 file systems. The ‘D’ option is only useful on Linux kernel 2.5.19 and later.

有些指令需要特定的系统环境才可以使用:

ext2,ext3 和 ext4 文件系统不支持 c 、s 和 u 属性j 选项仅对 ext3 和 ext4 文件系统有用D 选项仅在 Linux 内核2.5.19及更高版本上有用


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3