As a System administrator, creating users on multiple servers maybe something that you would do on a daily basis. It maybe an easy task to create a user on single server but imagine that you need to add a user on 100+ different Linux servers. Isn't it a tedious task? so let's create a bash script that automates it.
First, let us create a text file that includes all the server hostnames or IP addresses where you wish to add the user.
Here in this example, I've created a file servers.txt that includes the servers names ( here I have two servers):
Now take a look at the following addusers.sh bash script:
#!/bin/bash
servers=$(cat servers.txt)
echo -n "Enter the username: "
read userName
echo -n "Enter the user id: "
read userID
for i in $servers; do
echo $i
ssh $i "sudo useradd -m -u $userID $userName"
if [ $? -eq 0 ]; then
echo "User $userName added on $i"
else
echo "Error on $i"
fi
done
When you run addusers.sh, the script will first ask you to enter the username and the user id of the user who you want to add; then, it will loop over and connect to all the servers in the servers.txt file via SSH and add the requested user.
Let's run the addusers.sh script and see how it executes:
If you haven't enabled password-less login via SSH, it will prompt to enter the password to gain access to server.
The script ran successfully and testuser2 account was created on the two servers.
- You must have a valid account that has super user access on all the servers.
As a beginner to Bash Scripting, I found it really impressive to know that with bash scripting you can automate many boring, tedious task in Linux!