fix(ssh): 避免覆盖 authorized_keys 并防止重复添加

This commit is contained in:
code-server-usr committed 2026-08-24 11:54:41 +08:00
1 parent 6d8350311f
commit ea0a7b7e9b
1 file changed
+11 -2
+11 -2
View File
@@ -224,8 +224,17 @@ modify_authorized_keys() {
echo "正在修改 authorized_keys" echo "正在修改 authorized_keys"
mkdir -p /root/.ssh/ mkdir -p /root/.ssh/
AUTHORIZED_KEY="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDi6fLhEYp2mmUUBOB/6CA0iQYcwhAUVBwpbJJhK0fZmvmtrCrfkDvFtqw4WH0D/DgRtJNyoDfrQ2gm67FtFzu2ZfH0PtIEI6JWrh432qjQnAT5cuKbN3ghrjTHf08vjh0axxilSFtCXf5Gyv+ZnABil7GZAhJB5K/yBUMr6OD5fp4tvjAYe0t6ZIQb8vgd0dCXDGA3Rak1B7W24vDA1Col+Qvx5I7pfqiebkof7BbkfBYX5KZ/ArK0n1RV7wBjf6g/XkwRPvpCR5rz7s+UnMr2FFYqfQ1wkpKjo74KzAahFyy7UicM3e7OKfZvd8EmWBysIdKCcl9s/H9Z4Q/TDZsmnr68KweCvpqFVHfKS9CZ/7w/7zQhrXDhnysqt6nmp/moQLMax6b62++4X6E0gyopc2nlMT+QjIwRPl+DPC2UicWniOSAuSvpPxt8YXF4Zbpsg0efMQvHDrjQF6Ws9UIKVQeTBqij+TJ3w5aUbLEjPhrP5ia7Dtn7u/3IsosxW00= yanhao@yanhaodeMacBook-Pro.local" AUTHORIZED_KEY="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDi6fLhEYp2mmUUBOB/6CA0iQYcwhAUVBwpbJJhK0fZmvmtrCrfkDvFtqw4WH0D/DgRtJNyoDfrQ2gm67FtFzu2ZfH0PtIEI6JWrh432qjQnAT5cuKbN3ghrjTHf08vjh0axxilSFtCXf5Gyv+ZnABil7GZAhJB5K/yBUMr6OD5fp4tvjAYe0t6ZIQb8vgd0dCXDGA3Rak1B7W24vDA1Col+Qvx5I7pfqiebkof7BbkfBYX5KZ/ArK0n1RV7wBjf6g/XkwRPvpCR5rz7s+UnMr2FFYqfQ1wkpKjo74KzAahFyy7UicM3e7OKfZvd8EmWBysIdKCcl9s/H9Z4Q/TDZsmnr68KweCvpqFVHfKS9CZ/7w/7zQhrXDhnysqt6nmp/moQLMax6b62++4X6E0gyopc2nlMT+QjIwRPl+DPC2UicWniOSAuSvpPxt8YXF4Zbpsg0efMQvHDrjQF6Ws9UIKVQeTBqij+TJ3w5aUbLEjPhrP5ia7Dtn7u/3IsosxW00= yanhao@yanhaodeMacBook-Pro.local"
echo $AUTHORIZED_KEY >/root/.ssh/authorized_keys local authorized_keys_file=/root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
touch "$authorized_keys_file"
if ! grep -Fqx -- "$AUTHORIZED_KEY" "$authorized_keys_file"; then
# Keep an existing final line intact when it does not end with a newline.
if [ -s "$authorized_keys_file" ] && [ -n "$(tail -c 1 "$authorized_keys_file")" ]; then
printf '\n' >>"$authorized_keys_file"
fi
printf '%s\n' "$AUTHORIZED_KEY" >>"$authorized_keys_file"
fi
chmod 600 "$authorized_keys_file"
# wget -q -O /tmp/sshd_config https://script.yanhao.ren/downloads/sshd_config # wget -q -O /tmp/sshd_config https://script.yanhao.ren/downloads/sshd_config
# mv /tmp/sshd_config /etc/ssh/sshd_config # mv /tmp/sshd_config /etc/ssh/sshd_config
# service sshd restart # service sshd restart