Introduction
In this blog post, we'll delve into creating a powerful shell script to streamline user management and file backup tasks within a Linux environment. This script will offer a user-friendly interface for adding, deleting, and modifying users, as well as backing up critical directories.
Setting Up the Environment
Before we dive into the script, ensure you have a Linux system and a basic understanding of shell scripting. You'll need a text editor (like Vim, Nano, or Visual Studio Code) to write the script.
The Shell Script
Here's a breakdown of the script's functionality and code:
#!/bin/bash
#add a user
add_user() {
read -p "Enter username: " username
read -p "Enter password: " password
useradd -m -p "$password" $username
}
#delete an user
delete_user() {
read -p "Enter username to delete: " username
userdel -r $username
}
#change password
change_password() {
read -p "Enter username to modify: " username
read -p "Enter new password: " password
if [ -n "$password" ]; then
usermod -p "$password" $username
fi
}
#create a backup
backup() {
read -p "Enter directory to backup: " directory
timestamp=$(date +%Y%m%d_%H%M%S)
tar -czvf backup_$timestamp.tar.gz $directory
}
#main function
while true; do
echo "1. Add User"
echo "2. Delete User"
echo "3. Change Password"
echo "4. Backup Directory"
echo "5. Exit"
read -p "Enter your choice: " choice
case $choice in
1) add_user ;;
2) delete_user ;;
3) change_password ;;
4) backup ;;
5) exit 0 ;;
*) echo "Invalid choice" ;;
esac
done;
How it works:
User Management:
Adding Users: The
add_user
function prompts for a username and password, then creates the user using theuseradd
command.Deleting Users: The
delete_user
function takes a username and removes the user using theuserdel
command.Changing Passwords: The
change_password
function prompts for a username and new password, then updates the password using theusermod
command.
Backup Functionality:
- The
backup
function prompts for a directory to back up, creates a timestamped archive usingtar
and compresses it withgzip
.
- The
Running the Script:
Save the Script:
Save the script as a
.sh
file, for example, user_management.shMake it Executable:
Use the
chmod
command to grant execution permissions:chmod 744 user_management.sh #you can use what ever series of permission you want, #but i suggest not to give the user management access to other users or groups
Run the Script:
Execute the script using:
./user_management.sh
Conclusion
By automating these tasks with a shell script, you can significantly improve efficiency and reduce the risk of human error. Remember to tailor the script to your specific needs and to test it thoroughly before deploying it in a production environment.
you can access to this repository through the github, feel free to contribute to this project by submitting pull requests, add some additional features that are suitable or raising issues on GitHub.