Search code examples
powershellpasswordssudoubuntu-18.04windows-subsystem-for-linux

How can I add a sudo user to WSL using commands in powershell?


I am trying to automate the WSL setup using powershell scripts. I have Ubuntu 18.04 distro installed for WSL in my windows 10 system.

I want to run the following commands in powershell to setup a sudo user tec with password 1 in WSL.

Ubuntu1804 run useradd -m tec
Ubuntu1804 run usermod --password $(echo 1 | openssl passwd -1 -stdin) tec
Ubuntu1804 run usermod -aG sudo tec

The problems is, password is not set correctly with the second command. Trying to become the root user ends up in

 sudo: 3 incorrect password attempts

If I enter to WSL by typing bash from windows command prompt, and then execute the following command :

usermod --password $(echo 1 | openssl passwd -1 -stdin) tec

It sets the password correctly. After that I can become root user by entering the password 1 when prompted.

Can anyone help me to find where I am going wrong with the powershell script?


Solution

  • I got the answer. Just wrapping the encrypted password in the second command with single quote worked perfectly.

    Ubuntu1804 run usermod --password '$(echo 1 | openssl passwd -1 -stdin)' tec
    

    Now the powershell commands to create a sudo user tec with password 1 for WSL looks like :

    # Creates the user
    Ubuntu1804 run useradd -m tec
    
    # sets password for user
    Ubuntu1804 run usermod --password '$(echo 1 | openssl passwd -1 -stdin)' tec
    
    # adds user to the sudo group
    Ubuntu1804 run usermod -aG sudo tec