Apart from changing the rwxr-xr-x like permissions, some Linux filesystems have another way of protecting files. You cam make them IMMUTABLE, after which no program can change them. Not even if you have the right permissions. Python however does not support reading or writing the immutable attribute.
Inspired by yellowcrescent, I just wrote the following code snippet for my own use:
# Code from geeklab.info
import fcntl
from array import array
# FS constants - see /uapi/linux/fs.h in kernel source
# or <elixir.free-electrons.com/linux/latest/source/include/uapi/linux/fs.h>
FS_IOC_GETFLAGS = 0x80086601
FS_IOC_SETFLAGS = 0x40086602
FS_IMMUTABLE_FL = 0x010
def chattri(filename: str, value: bool):
with open(filename,'r') as f:
arg = array('L', [0])
fcntl.ioctl(f.fileno(), FS_IOC_GETFLAGS, arg, True)
if value:
arg[0]=arg[0] | FS_IMMUTABLE_FL
else:
arg[0]=arg[0] &~ FS_IMMUTABLE_FL
fcntl.ioctl(f.fileno(), FS_IOC_SETFLAGS, arg, True)
def lsattri(filename: str) -> bool:
with open(filename,'r') as f:
arg = array('L', [0])
fcntl.ioctl(f.fileno(), FS_IOC_GETFLAGS, arg, True)
return bool(arg[0] & FS_IMMUTABLE_FL)
f="/root/testfile"
print("Yes" if lsattri(f) else "No")
chattri(f,False)
print("Yes" if lsattri(f) else "No")
chattri(f,False)
print("Yes" if lsattri(f) else "No")
Use it as you like, at your own risk. If possible please link my website.
Keep in mind that only users with root-access can change file attributes.
© GeekLabInfo chattr and lsattr in Python is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info