【问题标题】:pipe value to sed and use it in the replace string管道值到 sed 并在替换字符串中使用它
【发布时间】:2019-07-06 23:58:55
【问题描述】:

我正在尝试以编程方式生成用户和密码,然后对密码进行哈希处理并将其存储在 grub 配置文件中

我现在有这个

# add a superuser account and password for the bootloader
## generate a secure password
pw=$(openssl rand -base64 32)

## create the new user for the bootloader and set the password as the secure password
useradd grub2superuseraccount
echo $pw | passwd grub2superuseraccount --stdin

## store the password to a TEMP file (needed to pass the password to grub2_mkpassword-pbkdf command, it will be deleted after)
cat << END >> ~/pfile
$pw
$pw
END

## generate the password hash and store it in the bootloader config file
cat ~/pfile | grub2-mkpasswd-pbkdf2 | sed -i "/password_pbkdf2/a password_pbkdf2 $THEVALUEOFTHEOUTPUTFROMTHEPIPE"

## delete the file with the password
rm ~/pfile 

如何将“grub2-mkpasswd-pbkdf2”的哈希密码输出传递给 sed 命令?

如果有另一种更优雅的方法,我会怎么做?

【问题讨论】:

标签: bash awk sed centos


【解决方案1】:

您可以使用 GNU/Bash read 来满足您的需求,例如:

cat ~/pfile | grub2-mkpasswd-pbkdf2 | (read THEVALUEOFTHEOUTPUTFROMTHEPIPE && sed -i "/password_pbkdf2/a password_pbkdf2 $THEVALUEOFTHEOUTPUTFROMTHEPIPE")

【讨论】:

    【解决方案2】:

    这是一个重构,它也避免了讨厌的临时文件。

    pw=$(openssl rand -base64 32)
    useradd grub2superuseraccount
    # Notice proper quoting
    echo "$pw" | passwd grub2superuseraccount --stdin
    # Collect output into a variable
    grubpw=$(printf '%s\n' "$pw" "$pw" | grub2-mkpasswd-pbkdf2)
    # Use the variable in sed -i
    sed -i "/password_pbkdf2/a password_pbkdf2 $grubpw" conffile
    

    您的问题并未指明conffile 的名称,因此显然将其替换为您实际要在sed -i 上运行的文件的名称。

    如果grub2-mkpasswd-pdkdf2 的输出可能包含换行符或其他有问题的字符,则可以在变量中添加一些转义。

    如果您真的需要使用管道,请查看xargs

    printf '%s\n' "$pw" "$pw" |
    grub2-mkpasswd-pbkdf2 |
    xargs -i sed -i "/password_pbkdf2/a password_pbkdf2 {}" conffile
    

    【讨论】:

    • 确实看起来更优雅,我会尝试一下!感谢大家的快速回复
    • 如果您有兴趣,我根据您的意见更新了问题,再次感谢!
    • 您的问题应该严格保持为一个问题。如果您想添加自己的答案,欢迎您这样做。 (您可以从revision history. 检索您的更改)
    【解决方案3】:

    如何将“grub2-mkpasswd-pbkdf2”的哈希密码输出传递给 sed 命令?

    通过命令替换,不需要管道:

    sed -i "/password_pbkdf2/c password_pbkdf2 $(grub2-mkpasswd-pbkdf2 < ~/pfile)" your_grub.conf
    

    请注意,我稍微更改了您的 sed 命令,使用 cc将整行挂到命令后面的内容,而不是 a 其中 a追加一个全新的行。

    【讨论】:

    • @Inian 对不起,我的意思是 command 替换。谢谢你的收获。
    猜你喜欢
    • 2021-03-15
    • 2017-11-21
    • 2021-05-16
    • 2021-03-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2020-07-28
    • 2017-02-08
    相关资源
    最近更新 更多