Adding an account via SSH not working with openssl

I am trying to add a user account to my remote server (running on Ubuntu 22.04) via SSH using below script:

#!/bin/bash

protect="y"
ssh -i ssh_key root@server.ip <<END
   sudo deluser testuser
   if [[ "$protect" =~ ^[yY]*$ ]]; then sudo useradd -p $(openssl passwd -1 "password") testuser && echo "User added successfully"; fi
END

read -n 1 -srp "Press any key to exit."

The confirmation message User added successfully is showing and the user is added normally. Except I can’t login to that account with these credentials.

When I try to execute these commands one by one directly on the server, everything works fine and I can login to that account, so I assumed it would be some quotes escaping issue, and I tried some variantes including:

""password""
""password""
""password""
""password""

But none worked.

Please help me.

Asked By: hiddeneyes02

||

Your command has a different output every time you run it. I use this command from this answer to demonstrate the problem:

openssl passwd -6 -salt xyz  password

The variables starting with $ in the output will be substituted:

$ openssl passwd -6 -salt xyz  password
$6$xyz$ShNnbwk5fmsyVIlzOf8zEg4YdEH2aWRSuY4rJHbzLZRlWcoXbxxoI0hfn0mdXiJCdBJ/lTpKjk.vu5NZOv0UM0
$ bash << EOF
echo $(openssl passwd -6 -salt xyz password)
EOF
/lTpKjk.vu5NZOv0UM0

You could run the openssl command on the remote host:

#!/bin/bash

protect="y"
if [[ "$protect" =~ ^[yY]*$ ]]; then 
   ssh -i ssh_key root@server.ip 'sudo useradd -p $(openssl passwd -1 "password") testuser && echo "User added successfully"'
fi


read -n 1 -srp "Press any key to exit."

Note the difference between:

$ ssh HOST 'echo "$(openssl passwd -6 -salt xyz  password)"'
$ ssh HOST echo "$(openssl passwd -6 -salt xyz  password)"
Answered By: ctx