Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically add user account AND password with a Bash script?

Tags:

linux

bash

passwd

People also ask

How do you put a username and password in a script?

You can quickly write a shell script that reads username, password from the keyboard, and add a username to the /etc/passwd and store encrypted password in /etc/shadow file using useradd command.

How do I prompt a password in bash?

#!/bin/bash echo "Enter Username : " # read username and echo username in terminal read username echo "Enter Password : " # password is read in silent mode i.e. it will # show nothing instead of password. read -s password echo echo "Your password is read in silent mode."


You could also use chpasswd:

echo username:new_password | chpasswd

so, you change password for user username to new_password.


You can run the passwd command and send it piped input. So, do something like:

echo thePassword | passwd theUsername --stdin

I was asking myself the same thing, and didn't want to rely on a Python script.

This is the line to add a user with a defined password in one bash line:

useradd -p $(openssl passwd -crypt $PASS) $USER

The code below worked in Ubuntu 14.04. Try before you use it in other versions/linux variants.

# quietly add a user without password
adduser --quiet --disabled-password --shell /bin/bash --home /home/newuser --gecos "User" newuser

# set password
echo "newuser:newpassword" | chpasswd

I liked Tralemonkey's approach of echo thePassword | passwd theUsername --stdin though it didn't quite work for me as written. This however worked for me.

echo -e "$password\n$password\n" | sudo passwd $user

-e is to recognize \n as new line.

sudo is root access for Ubuntu.

The double quotes are to recognize $ and expand the variables.

The above command passes the password and a new line, two times, to passwd, which is what passwd requires.

If not using variables, I think this probably works.

echo -e 'password\npassword\n' | sudo passwd username

Single quotes should suffice here.