Taking a user password in Bash is an important task. One can utilize the read command to read passwords securely. Moreover, the openssl command provides the opportunity to encrypt passwords in an irreversible way. This article discusses three different cases of how to read a user password in Bash considering its security concern.
Key Takeaways
- Reading password from user prompt.
- Reading passwords securely using -s.
- Securing passwords using hash encryption.
Free Downloads
3 Cases of Reading Password in Bash
The read command is commonly used to gather user input. Similarly, it’s handy for reading passwords while keeping them hidden with the -s option. Moreover one can read passwords from files. Let’s explore different scenarios of reading passwords in Bash.
Case 1: Reading Password from Prompt
The common approach to reading a password is by prompting the requirement of the password to the user. In the following script, I will show you how to read user password from the prompt using the read command.
❶ At first, launch an Ubuntu Terminal.
❷ Write the following command to open a file named prompt.sh in the build-in nano editor:
nano prompt.sh
- nano: Opens a file in the Nano text editor.
- prompt.sh: Name of the file.
Script (prompt.sh) >
#!/bin/bash
# Prompt the user for a password
read -p "Enter your password: " password
echo # Move to a new line after reading the password
# Read the new username
read -p "Enter the username to add: " new_username
# Use sudo to add a new user
echo "$password" | sudo -S useradd "$new_username"
# Check if the user was added successfully
if [ $? -eq 0 ]; then
echo "User $new_username added successfully"
else
echo "Failed to add user $new_username"
fi
The script prompts the user to enter password using the read command. Then the user is prompted to provide a username for the new account. The script then employs the sudo command, along with the provided password, to add a user using the useradd command. Finally, it displays a confirmation message based on the exit status of the useradd command.
❹ Use the following two commands to make both file executable:
chmod u+x prompt.sh
- chmod: Changes permissions.
- u+x: Giving the owner executing permission.
- prompt.sh: Name of the script.
./prompt.sh
The image shows that the program first seeks the password of the user which is given as Ubuntu. Then it executes commands for adding a new user using the given password.
Case 2: Reading Password Without Displaying It to the User in Bash
The read command can be employed to capture a user’s password without displaying it on the screen. This approach adds an extra layer of protection and keeps passwords hidden from others’ sight. -s option of the read command is used for this purpose.
Script (hiddenpass.sh) >
#!/bin/bash
# Prompt the user for a password
read -p -s "Enter your password: " password
echo # Move to a new line after reading the password
# Read the new username
read -p "Enter the username to add: " new_username
# Use sudo to add a new user
echo "$password" | sudo -S useradd "$new_username"
# Check if the user was added successfully
if [ $? -eq 0 ]; then
echo "User $new_username added successfully"
else
echo "Failed to add user $new_username"
fi
The script prompts the user to input password using the -s flag, ensuring the password remains unrevealed on the screen. Subsequently, the script prompts for a username. The provided password is then used to execute the sudo -S useradd command, adding the new user with the specified username. Finally, it displays a confirmation message based on the exit status of the useradd command whether the new user is created successfully or not.
Run the hiddenpass.sh script by the following command:
./hiddenpass.sh
You can see user Bin is created successfully after reading the system password from the current user. However, the given password is not displayed while reading it from the user. The -s option of read command successfully hides the password.
Case 3: Reading Password from a Password File
Imagine having a password file where you’ve stored all your passwords. Instead of inputting the password manually through a prompt, a program can retrieve it directly from the saved file. Let’s see how it works.
Script (filepass.sh) >
#!/bin/bash
file="password.txt"
# Use 'grep' to find the password
password=$(grep "Linux :" "$file" | awk -F ': ' '{print $2}')
# Check if the password was found
if [ -z "$password" ]; then
echo "Password not found."
exit 1
else
echo "System successfully finds the password."
fi
# Read the new username
read -p "Enter the username to add: " new_username
# Use sudo to add a new user with the extracted password
echo "$password" | sudo -S useradd "$new_username"
# Check if the user was added successfully
if [ $? -eq 0 ]; then
echo "User $new_username added successfully"
else
echo "Failed to add user $new_username"
fi
This Bash script reads the content of password.txt file and attempts to find a password associated with Linux. It uses the grep command to search for a line containing “Linux :” and then employs awk to extract the password field following the colon.
The script utilizes the extracted password as input to the sudo -S useradd command, attempting to add a new user with the specified username using the extracted password.
After the user addition attempt, the script checks the exit status of the useradd command. If the exit status is 0, it prints a success message indicating that the user was added; otherwise, it prints a failure message.
Now see the password.txt file first using the command below:
cat password.txt
As you can see there are passwords for various applications stored in the password.txt file. The password for Linux is in the third line of the file.
This time run the filepass.sh script by the following command:
./filepass.sh
As you can see the program reads the password of Linux from the file. Using this password it successfully added a new user Jemmy to the system.
Echoing * (Asterisk) for Each Character while Reading Password
Someone may be confused whether a program takes password or not if nothing is displayed on the terminal. So, instead of displaying nothing one can use the following script to display an asterisk for each inputted character of the password.
Script (asterisk.sh) >
#!/bin/bash
password=""
prompt="Enter your password: "
while IFS= read -p "$prompt" -r -s -n 1 letter; do
if [[ $letter == $'\0' ]]; then
break
fi
password="$password$letter"
prompt="*"
done
echo -e "\nPassword entered: $password"
The script initializes an empty password variable and seeks the password from the user. Then it enters in a while loop where the read command is used to capture individual characters of user input.
-r -s -n 1 ensures that the input is read silently by avoiding backslashes and reading only a single character at a time. An asterisk is displayed for each appended character to the password variable.
Run the asterisk.sh script by the following command:
./asterisk.sh
As evident, the script displays asterisks to validate each user input. In this instance, the user entered Ubuntu as the password, resulting in the display of six asterisks. This pattern confirms to the user that their input has been accurately captured.
How to Encrypt Password Using Hash Algorithm in Bash
One can encrypt password using openssl command for public servers. It uses various hash algorithms such as SHA-256 algorithm and a randomly generated salt to encrypt a password. Hashing is a one-way function. It means that once a password is hashed, it isn’t easy to convert it back to the original.
Script (encryption.sh) >
#!/bin/bash
# Generate a random salt
salt=$(openssl rand -base64 8)
# Get the password from the user
read -p "Enter your password: " password
# Combine the password and salt, then hash using SHA-256
hashed_password=$(echo -n "$password$salt" | openssl dgst -sha256 -binary | base64)
echo "Salt: $salt"
echo "Hashed Password: $hashed_password"
In this Bash script a random 8-byte salt is generated using the openssl command. The user is prompted to input a password. The script then combines the user’s password and the generated salt.
This concatenated string is hashed using the SHA-256 algorithm through the openssl dgst command. The resulting binary hash is then encoded in base64 format to generate the final hashed password.
Run the encryption.sh script by the following command:
./encryption.sh
Here the password Ubuntu is hashed using openssl command. The encrypted password is displayed in the image above.
Conclusion
In conclusion, one can read a user password in Bash in various ways with different layers of protection. Moreover, one can store encrypted passwords using hash-based algorithms. I believe from now on you can take user password securely as well as encrypt password where necessary.
People Also Ask
Related Articles
- How to Get Date in Bash [2 Methods with Examples]
- How to Print Time in Bash [2 Quick Methods]
- How to List Users in Bash [2 Easy Ways]
- How to Get Current Time in Bash [4 Practical Cases]
- How to Use Date Format in Bash [5 Examples]
- How to Get Timestamp in Bash [2 Practical Cases]
- How to Copy and Paste in Bash [2 Methods & Cases]
- How to Send Email in Bash [2 Easy Methods]
- Bash Script to Send Email with Attachment [Step-by-Step Guide]
- How to Get IP Address in Bash [3 Methods]
- How to Find and Replace String in Bash [5 Methods]
- How to Get Script Name Using Bash Script? [3 Easy Ways]
- How to Call Another Script in Bash [2 Methods]
- How to Generate UUID in Bash [3 Simple Methods]
- 3 Easy Ways to Write to a File in Bash Script
- How to Write the Output to a File in Bash Script [5 Practical Cases]
- How to Create a List in Bash Scripts? [2 Easy Methods]
- How to Clear History in Bash [2 Practical Cases]
- How to Clear Screen Using Bash Script? [2 Effective Methods]
- How to Check Ubuntu Version Using Bash Scripts? [2 Methods]
<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial