如何阻止Linux系统文件被root权限脚本修改?——Debian服务器authorized_keys条目丢失临时解决方案咨询
Got it, let's get you a quick, bulletproof temporary fix to stop that authorized_keys file from being overwritten—even by root-level scripts. Later on, you'll want to dig into the root cause (like config management tools, cron jobs, or system scripts that're updating the file), but for now, here are two reliable methods:
Method 1: Use the Immutable File Attribute (chattr +i)
This sets a kernel-level flag that prevents any modification to the file—including deletion, overwriting, or renaming—until you explicitly remove the flag.
First, make a backup just in case:
cp ~/.ssh/authorized_keys ~/.ssh/authorized_keys.bakApply the immutable attribute (needs sudo):
sudo chattr +i ~/.ssh/authorized_keysVerify the attribute is set:
lsattr ~/.ssh/authorized_keysYou should see an
iin the output (e.g.,----i--------e----- ~/.ssh/authorized_keys).When you need to modify the file later (after fixing the root cause), remove the attribute first:
sudo chattr -i ~/.ssh/authorized_keysDon't forget to re-apply
+ionce you're done editing!
Method 2: Read-Only Bind Mount
This mounts the file itself as read-only, which blocks any write attempts. It's a bit more "invisible" than chattr and can be persisted across reboots if needed.
- Apply the read-only mount immediately:
sudo mount --bind ~/.ssh/authorized_keys ~/.ssh/authorized_keys sudo mount -o remount,ro ~/.ssh/authorized_keys - To make this persist after reboot, add a line to
/etc/fstab(replace/home/your-userwith your actual home directory path):echo "/home/your-user/.ssh/authorized_keys /home/your-user/.ssh/authorized_keys none bind,ro 0 0" | sudo tee -a /etc/fstab - To undo this later:
sudo mount -o remount,rw ~/.ssh/authorized_keys sudo umount ~/.ssh/authorized_keys # If you added it to fstab, remember to remove that line too
A Quick Note on Root Cause
Once you've locked down the file, don't forget to track down what's overwriting it! Check these places first:
- Cron jobs or systemd timers (run
crontab -lfor your user,sudo crontab -lfor root, andsystemctl list-timers) - Configuration management tools like Ansible, Puppet, or Chef (look for playbooks/manifests that manage SSH keys)
- System scripts in
/etc/cron.daily,/etc/cron.hourly, or similar directories
内容的提问来源于stack exchange,提问作者k0pernikus

