GnuPG,从 bash 脚本提示输入密码

0 bash gpg

如何从 bash 脚本提示输入密码?

我收到此错误消息:problem with the agent: Inappropriate ioctl for device

#!/bin/bash

fname="/home/user/elist.txt"
while IFS= read -r file
do
    tar czf "$file".tar.gz "$file"
    gpg --passphrase-fd 0 --no-symkey-cache --symmetric --cipher-algo AES256 "$file".tar.gz
done < "$fname"
Run Code Online (Sandbox Code Playgroud)

fra*_*san 5

鉴于--passphrase-fd 0,gpg正在尝试从文件 \xe2\x80\x94 读取密码"$fname",因为在while循环内,这就是文件描述符0重定向的源。
\n您有一些选项可以使其发挥作用:

\n
    \n
  • 将整个循环括在大括号中,将标准输入复制到新的文件描述符并将其用作--passphrase-fd\ 的参数:

    \n
    fname="/home/user/elist.txt"\n{\n  while IFS= read -r file\n  do\n      tar czf "$file".tar.gz -- "$file"\n      gpg --passphrase-fd 3 --no-symkey-cache --symmetric --batch \\\n        --cipher-algo AES256 --pinentry-mode loopback -- "$file".tar.gz\n  done < "$fname"\n} 3<&0\n
    Run Code Online (Sandbox Code Playgroud)\n
  • \n
  • 显式打开一个新的文件描述符elist.txt并从中重定向read\ 的标准输入(而不是重定向整个循环的标准输入):

    \n
    exec 3<"/home/user/elist.txt"\nwhile <&3 IFS= read -r file\ndo\n    tar czf "$file".tar.gz -- "$file"\n    gpg --passphrase-fd 0 --no-symkey-cache --symmetric --batch \\\n      --cipher-algo AES256 --pinentry-mode loopback -- "$file".tar.gz\ndone\nexec 3<&-\n
    Run Code Online (Sandbox Code Playgroud)\n
  • \n
  • 显式打开一个新的文件描述符/dev/tty并使用它代替0--passphrase-fd选项的参数(如果您的脚本从终端交互运行,这很好;如果密码短语来自其他内容,则它可能无法按预期工作) :

    \n
    fname="/home/user/elist.txt"\nexec 3</dev/tty\nwhile IFS= read -r file\ndo\n    tar czf "$file".tar.gz -- "$file"\n    gpg --passphrase-fd 3 --no-symkey-cache --symmetric --batch \\\n      --cipher-algo AES256 --pinentry-mode loopback -- "$file".tar.gz\ndone < "$fname"\nexec 3<&-\n
    Run Code Online (Sandbox Code Playgroud)\n

    作为更简洁的替代方案,您可以使用仅从/dev/ttyfor重定向标准输入,从而避免使用命令。gpg0</dev/tty gpg --passphrase-fd 0 ...exec

    \n
  • \n
  • 假设您已正确配置gpg-agent(例如,在某些 Linux 发行版上,代理是套接字激活的 systemd 服务,用于pinentry与用户交互并在虚拟终端和图形会话中开箱即用),只需避免使用--passphrase-fd

    \n
    fname="/home/user/elist.txt"\nwhile IFS= read -r file\ndo\n    tar czf "$file".tar.gz -- "$file"\n    gpg --no-symkey-cache --symmetric \\\n      --cipher-algo AES256 -- "$file".tar.gz\ndone < "$fname"\n
    Run Code Online (Sandbox Code Playgroud)\n
  • \n
\n

请注意,我在使用的命令行中添加了和,--batch因为引用手册--pinentry-mode loopbackgpg--passphrase-fd

\n
\n

...自版本 2.0 起,仅当也给出了该选项时才使用此密码--batch。从版本 2.1 开始,--pinentry-mode还需要设置为loopback.

\n
\n