Linux does not provide the chflags
syscall, so Python does not provide the wrapper os.chflags()
.
The chattr
command uses the code (e2fsprogs-1.42.13
's lib/e2p/fsetflags.c
):
fd = open (name, OPEN_FLAGS);
if (fd == -1)
return -1;
f = (int) flags;
r = ioctl (fd, EXT2_IOC_SETFLAGS, &f);
if (r == -1)
save_errno = errno;
close (fd);
to set the extended attributes for a file, so if you port that to Python (and use some C to extract the value for EXT2_IOC_SETFLAGS
from ext2fs/ext2_fs.h
), you can do something like:
#!/usr/bin/python2
import fcntl
import os
import struct
# Taken from ext2fs/ext2_fs.h.
EXT2_IMMUTABLE_FL = 0x00000010
EXT2_IOC_SETFLAGS = 0x40086602
fd = os.open('/var/tmp/testfile', os.O_RDWR)
f = struct.pack('i', EXT2_IMMUTABLE_FL)
fcntl.ioctl(fd, EXT2_IOC_SETFLAGS, f);
os.close(fd)
Et voilà:
[tim@passepartout ~]$ lsattr /var/tmp/testfile
----i----------- /var/tmp/testfile
[tim@passepartout ~]$
But for all practical purposes it is probably much more prudent to execute chattr(1)
as a child process than to turn the proof-of-concept above into something that runs reliably without maintenance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…