我的目标是自动更新authorized_keys 文件中的ssh 密钥。由于限制,我无法使用 ansible,这会简单得多。
步骤:
一切正常,除了它会删除最后一个匹配的键:
array1=(
"ssh-ed25519 AAAAC3... key1"
"ssh-ed25519 AAAAC3NzaC1l key2"
);
path=".ssh/authorized_keys"
mapfile -t array2_from_file < <(cat "$path")
escape_sed_pattern() {
printf '%s\n' "$1" | sed 's/[\\/&]/\\&/g'
}
for key in "${array2_from_file[@]}"; do
if ! [[ " ${array1[@]} " =~ " $key " ]]; then
echo "To be deleted: $key"
escaped_key=$(escape_sed_pattern "$key")
# Remove the key from the authorized_keys file
sed -i "/$escaped_key/d" "$path"
fi
done
听起来你想做的就是这样的事情,未经测试:
#!/usr/bin/env bash
path=".ssh/authorized_keys"
awk '
BEGIN {
split("ssh-ed25519 AAAAC3... key1" RS\
"ssh-ed25519 AAAAC3NzaC1l key2",
tmp, RS)
for ( i in tmp ) {
array1[tmp[i]]
}
}
$0 in array1 {
print "To be deleted:", $0
next
}
{ print }
' "$path"