How to copy all Immutable files attribute from one server to another server
In this tutorial we’ll learn how to copy immutable files from one server to another with simple command and bash script.
Immutable files in Linux are files that cannot be modified, renamed, deleted, or otherwise altered once they are marked as immutable. This feature is typically used for system files or critical configuration files to prevent accidental or unauthorized modifications. The immutability attribute can be set using the chattr
command in Linux.
You’ve noticed when copying files via rsync or cp the immutable files with i attribute doesn’t get copied to destination location. To fix this issue I’ve created wrapper commands and creating a bash file which will restore the attributes.
an example of how you can use the lsattr
command:
$ lsattr myfile.txt ----i---------- myfile.txt
In this example, the lsattr
command is used to list the attributes of the file myfile.txt
. The output ----i----------
indicates that the file has the immutable attribute set (i
). This means the file cannot be modified, renamed, or deleted until the attribute is removed using the chattr
-i command.
First run this command it will list all the immutable files and folders in /home/test.sh
location :
lsattr -aR /home 2>/dev/null | awk '{ print $1 " " $2 }' | grep -e "----i" | sed 's/^[^ ]* / /' > /home/test.sh | chmod +x /home/test.sh && sed -i 's/^/chattr +i /' /home/test.sh
Then copy the /home/test.sh file to remote destination server (if you want to make changes in remote server) and run the bash file :
sh /home/test.sh
that’s it it will restore the immutable attributes
Only if the path is different from source to destination :
If you rsync the files and folder to different directory just change the path in bash script via sed or via notepad ++ or other similar text editor and then run the bash
for example with sed if you want to change the /home directory to something /backup/dir/destination or you copied in another location use this command :
sed -i 's#/home#/backup/dir/destination#g' /home/test.sh
or to single folder in backup dir:
sed -i 's#/home#/backup#g' /home/test.sh
after you changed the directory path run the test.sh : sh /home/test.sh
Hope this helps to preserve the immutable attributes for you.