bash - 管道值到 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 命令?
或者
如果有另一种方法可以更优雅地做到这一点,我将如何去做呢?
解决方案
这是一个重构,它也避免了讨厌的临时文件。
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
推荐阅读
- javascript - Chart.js:从画布中获取图表数据
- android - Koin - Android 的嵌套范围问题
- scala - Avro GenericRecord 到嵌套 POJO
- jenkins-x - jx 失败并出现 BadRequestException 400 Invalid value
- python-3.x - 单密钥加密和多密钥解密
- php - Laravel yajra 数据表:将所有整数值作为字符串返回
- spring - @JsonManagedReference 和 @JsonBackReference 无法从 jsonbackreference 模型中获取关系数据
- html - 如何在表格中的 td 内使用边距但不使用边框折叠:分离
- r - ggplot 指定经度/纬度轴中断
- r - 使用 quadprog 的多项式回归