脚本可以在 shell 提示时提供输入吗?

can a script provide input when prompted by shell?

假设我想制作一堆充满乱码的文件。 如果我想要一个乱码文件,然后使用 ccrypt 加密它,我可以这样做:

$ echo "12 ddsd23" > randomfile.txt, 现在使用 ccrypt:

$ ccrypt -e randomfile.txt
Enter encryption key: 
Enter encryption key: (repeat)

如您所见,系统提示我输入密钥。

我想自动执行此操作并创建一堆乱码文件。

python 中的脚本产生随机乱码:

import random as rd
import string as st

alphs = st.ascii_letters
digits = st.digits
word = ""

while len(word) < 1000:
    word += str(rd.choices(alphs))
    word += str(rd.choices(digits))

print(word)

现在 运行 来自 bash 脚本,将乱码保存到 file:

#!/bin/bash

count=1

while [ $count -le 100 ]
do
  python3 /path/r.py > "file$count.txt"
  ccrypt -e "file$count.txt"
  ((count=count+1))
done

问题,如你所见:

$ bash random.sh 
Enter encryption key:

ccrypt 没有提供密码短语作为参数的选项。

问题:当 shell 提示输入密码时,bash 脚本有没有办法提供密码?

我知道这可以通过在 python 中进行加密来解决,但我很好奇是否可以使用 bash.

来完成这样的事情

如果重要:ccrypt 有一个选项可以只要求一个提示。

您需要在 bash 代码中使用 yes 命令。基本上,此命令将在需要时为脚本(即 ccrypt)提供输入。查看 here 了解更多信息。

[已编辑]

我原来的答案建议做:

printf "$PASSPHRASE\n$PASSPHRASE\n" | ccrypt -e "file$count.txt"

这是通用解决方案,应该可以与许多需要将某些输入传递到其 STDIN 的工具一起使用;但无论出于何种原因,它似乎都不适用于 ccrypt

但是,ccrypt 也有以不同(非交互式)方式提供密码的选项:

$ ccrypt --help
    ...
    -K, --key key         give keyword on command line (unsafe)
    -k, --keyfile file    read keyword(s) as first line(s) from file
    ...

这是一个使用 -K 的示例。请注意,它是“不安全的”,因为如果您在交互式 shell 或 运行 脚本中使用 -x 执行此命令(以打印每个已执行的命令),密码可能会以~/.bash_history 或分别在某些日志中,因此将密码短语转储到文件并使用 -k 以防万一。

#!/bin/bash

# read the passphrase, do not display it to screen
read -p "Please provide a passphrase:" -s PASSPHRASE

count=1

while [ $count -le 100 ]
do
  python script.py > "file$count.txt"
  ccrypt -e "file$count.txt" -K "$PASSPHRASE"
  ((count=count+1))
done