首页 > 解决方案 > 管道值到 sed 并在替换字符串中使用它

问题描述

我正在尝试以编程方式生成用户和密码,然后对密码进行哈希处理并将其存储在 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 命令?

或者

如果有另一种方法可以更优雅地做到这一点,我将如何去做呢?

标签: bashawksedcentos

解决方案


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

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

推荐阅读