使用 sed 删除两个数组中的差异(更新 ssh 密钥)

问题描述 投票:0回答:1

我的目标是自动更新authorized_keys 文件中的ssh 密钥。由于限制,我无法使用 ansible,这会简单得多。

步骤:

  • 从文件中读取密钥
  • 比较按键
  • 打印出将被删除的密钥,因为它不在提供的数组中
  • 删除键

一切正常,除了它会删除最后一个匹配的键:

  • 如果 array1 和 array2_from_file 中有两个键匹配,则会删除第二个键
  • 更具体地说,它将删除“key2”(见下文)

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
bash shell ssh sed
1个回答
0
投票

听起来你想做的就是这样的事情,未经测试:

#!/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"
© www.soinside.com 2019 - 2024. All rights reserved.