将值传递给sed并在替换字符串中使用

8
我将尝试编写程序来自动生成用户名和密码,然后对密码进行哈希处理并将其存储在 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命令?

或者

如果有更加简洁的方法,我该如何实现?


你可以使用进程替换来实现你的目标。 - Poshi
我正在使用这个例子,看起来它允许这样做https://github.com/ryran/burg2-mkpasswd-pbkdf2/blob/master/README.md - Ian
如果您的脚本已经在内存中包含了该变量,那么将密码写入文件并不能真正提高安全性。 - tripleee
3个回答

5
这是一项重构技术,同时避免了烦人的临时文件。
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

这看起来确实更加优雅,我会尝试一下!感谢大家的快速回复。 - Ian
如果您感兴趣的话,我已经根据您的输入更新了问题,再次感谢! - Ian
你的问题应该保持严格的问题形式。如果你想添加自己的答案,欢迎这样做。(你可以从修订历史记录中检索你的更改。) - tripleee

2
如何将从“grub2-mkpasswd-pbkdf2”输出的哈希密码传递给sed命令?
通过命令替换,不需要管道:
sed -i "/password_pbkdf2/c password_pbkdf2 $(grub2-mkpasswd-pbkdf2 < ~/pfile)" your_grub.conf

请注意,我稍微修改了您的sed命令,使用c将整行更改为命令后面的内容,而不是a附加一个全新的行。

1
@Inian 抱歉,我的意思是“命令”替换。感谢你的指正。 - Adrian

1
你可以使用GNU/Bash的read来实现你的需求,例如:
cat ~/pfile | grub2-mkpasswd-pbkdf2 | (read THEVALUEOFTHEOUTPUTFROMTHEPIPE && sed -i "/password_pbkdf2/a password_pbkdf2 $THEVALUEOFTHEOUTPUTFROMTHEPIPE")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接