I am trying to programmatically generate a user and password, then hash the password and store it in the grub config file
I currently have this
# 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
How can I pass the hashed password output from 'grub2-mkpasswd-pbkdf2' to the sed command?
OR
If there is another way to do this more elegantly, how would I go about doing that?
Here's a refactoring which also avoids the pesky temporary file.
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
Your question doesn't indicate the name of conffile
so obviously replace that with the name of the file you actually want to run sed -i
on.
If the output from grub2-mkpasswd-pdkdf2
could contain newlines or other problematic characters, maybe add some escaping to the variable.
If you really genuinely require a pipe to be used, maybe look into xargs
.
printf '%s\n' "$pw" "$pw" |
grub2-mkpasswd-pbkdf2 |
xargs -i sed -i "/password_pbkdf2/a password_pbkdf2 {}" conffile
You can use GNU/Bash read
to reach your needs, for instance:
cat ~/pfile | grub2-mkpasswd-pbkdf2 | (read THEVALUEOFTHEOUTPUTFROMTHEPIPE && sed -i "/password_pbkdf2/a password_pbkdf2 $THEVALUEOFTHEOUTPUTFROMTHEPIPE")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With