我们可以将gpg --search-keys 命令的std 和err 输出存储到specifying 2>&1 的变量中,然后对这些变量进行处理。例如,获取公钥 id 或 *.amazon.com 电子邮件地址:
pubkeyids=$(gpg --batch --keyserver hkp://keyserver.ubuntu.com --search-keys amazon.com 2>&1 | grep -Po '\d+\s*bit\s*\S+\s*key\s*[^,]+' | cut -d' ' -f5)
正则表达式在regex101.com 上有完整的解释。我们可以通过它们的 ID 自动搜索密钥,并通过解析该输出使用 bash 将它们添加到密钥环中。作为说明,我创建了the following GitHub gist 来托管下面的代码。
示例地址列表example.csv:
| First Name |
Last Name |
Email Address |
| Hi |
Bye |
hi@bye.com |
| Yes |
No |
yes@no.com |
| Why |
Not |
why@not.com |
然后我们可以将 csv 路径传递给 bash 脚本,该脚本将在 csv 中添加属于电子邮件地址的所有键:
$ getPubKeysFromCSV.sh ~/example.csv
这是上述想法的一个实现,getPubKeysFromCSV.sh:
# CSV of email address
csv=$1
# Get headers from CSV
headers=$(head -1 $csv)
# Find the column number of the email address
emailCol=$(echo $headers | tr ',' '\n' | grep -n "Email Address" | cut -d':' -f1)
# Content of the CSV at emailCol column, skipping the first line
emailAddrs=$(tail -n +2 $csv | cut -d',' -f$emailCol)
gpgListPatrn='(?<entropy>\d+)\s*bit\s*(?<algo>\S+)\s*key\s*(?<pubkeyid>[^,]+)'
# Loop through the array and get the public keys
for email in "${emailAddrs[@]}"
do
# Get the public key ids for the email address by matching the regex gpgListPatt
pubkeyids=$(gpg --batch --keyserver hkp://keyserver.ubuntu.com --search-keys $email 2>&1 | grep -Po $gpgListPatrn | cut -d' ' -f5)
# For each public key id, get the public key
for pubkeyid in $pubkeyids
do
# Add the public key to the local keyring
recvr=$(gpg --keyserver hkp://keyserver.ubuntu.com --recv-keys $pubkeyids 2>&1)
# Check exit code to see if the key was added
if [ $? -eq 0 ]; then
# If the public key is added, do some extra work with it
# [do stuff]
fi
done
done
如果我们愿意,我们可以通过在成功添加公钥后验证循环体中的文件签名来使getPubKeysFromCSV.sh 更复杂。除了 CSV 路径,我们将签名路径和文件路径分别作为参数二和三传递:
$ getPubKeysFromCSV.sh ~/example.csv ./example.file.sig ./example.file
这里是更新后的脚本差异diff:
--- original.sh
+++ updated.sh
@@ -1,6 +1,12 @@
# CSV of email address
csv=$1
+# signature file
+sig=$2
+
+# file to verify
+file=$3
+
# Get headers from CSV
headers=$(head -1 $csv)
@@ -22,5 +28,17 @@
recvr=$(gpg --keyserver hkp://keyserver.ubuntu.com --recv-keys $pubkeyids 2>&1)
# Check exit code to see if the key was added
+ if [ $? -eq 0 ]; then
+ verify=$(gpg --batch --verify $sig $file 2>&1)
+ # If the signature is verified, announce it was verified
+ # else, print error not verified and exit
+ if [[ $verify =~ "^gpg: Good signature from" ]]; then
+ echo "$file was verified by $email using $pubkeyid"
+ else
+ printf '%s\n' "$file was unable to be verified" >&2
+ exit 1
+ fi
+ fi
done
done