【问题标题】:pipe output from interactive command to less将交互式命令的输出通过管道传输到 less
【发布时间】:2013-08-23 02:13:46
【问题描述】:

我想做类似的事情

openssl enc -d -aes256 -in somefile | less

openssl 需要来自stdin 的密码。当涉及到less 时,这一切都会变得一团糟。

有没有办法从交互式命令中获取输出(例如 openssl 要求输入密码)并将输出通过管道传输到 less

或者有没有更好的使用 bash 脚本的技术?

【问题讨论】:

  • 以下方法可行,但我希望找到一种不使用临时文件的方法...$tmp_file=$(mktemp); openssl enc -d -in somefile > $tmp_file; less $tmp_file; rm $tmp_file
  • 我一直使用rsync 而不是ssh,并且通常没有问题。当事情确实变得混乱时,这似乎是一个时间问题 - 有一段时间没有发生,但我记得,如果 rsync 在询问密码时速度很慢,事情就会变得混乱。

标签: bash openssl pipe less-unix


【解决方案1】:

也许让 shell 脚本请求密钥,然后将密钥存储在临时文件中,并使用 openssl 的 -kfile 选项找到它。希望你的 openssl 版本支持 -kfile。

我会担心它的安全性,但稍加注意,安全漏洞可能比您想象的要小。 (但是你相信你的系统管理员和 sudoers...吗?)

#!/bin/bash

INFILE=somefile

read -s -p "Enter key for $INFILE: " key
echo

# write the key to a temp file; use mktemp(1)
# for safer creation of a privately-owned file.
#
TMPKEY=$(mktemp -t) || exit 1
echo "$key" > "$TMPKEY"

# will remove the temp file on script exit
trap 'rm -f "$TMPKEY"' EXIT

# remove the key file a couple seconds after openssl runs
(sleep 2; rm -f "$TMPKEY") &

openssl enc -d -aes256 -in "$INFILE" -kfile "$TMPKEY" | less

[ -f "$TMPKEY" ] && rm -f "$TMPKEY"
trap - EXIT

# rest of script...

exit 0

【讨论】:

  • 请不要忘记在变量周围使用双引号。将$TMPKEY 替换为"$TMPKEY"。这非常重要,因为如果文件包含空格字符,那么它将被拆分为两个单独的参数。例如:myFile='my awesome file' rm "$myFile" 将删除一个名为my awesome file 的文件,这是正确。但是rm $myFile 将删除三个文件:myawesomefile,这是错误且不可预测的,除非你真的知道自己在做什么。
  • 一般来说,一个非常好的规则。在示例脚本的十几行中创建并使用 TMPKEY 变量后,我知道它不包含空格($$ 解析为所有数字)。但正如您所说,大多数脚本应该使用更安全的技术:引用包含单个、任意路径名的变量。
  • 重点是您的脚本是一个示例,很可能人们会根据自己的喜好更改变量,但他们并不期望它会因为目录中的空格而失败。你能把它修好,让我投票吗?
  • 编辑为使用 mktemp(1) 来选择临时文件名并创建它,因此不需要子 shell 和 umask 技术。引用变量存储文件名。
【解决方案2】:

你可以试试这个:

echo 'mypassword' | openssl enc -d -aes256 -in somefile | less

但这看起来并不安全。

我没有尝试过以这种方式运行openssl,但如果它过于冗长并且之前的代码无法运行,那么您可以随时尝试使用expect。这是一个例子:

expect -c '
    spawn yourscript
    expect "Please enter your password:"
    send "$PASSWORD"
'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-17
    • 2018-08-18
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多