Bash is a Unix shell and command language that is used to automate tasks and perform system administration. In this blog post, we will take a look at a simple bash script that is used to delete a specific user from a list of remote servers.
#!/bin/bash | |
#IP list of respective hosts in text file | |
file=iplist.txt | |
#Mention the user which you want to delete | |
user=username | |
for server in $(cat iplist.txt) | |
do | |
#Connect to the remote server and delete the user | |
ssh root@$server "userdel $user | rm -rvf /home/$user" | |
#Check if the user was deleted successfully | |
if [ $? -eq 0 ] | |
then | |
echo "User '$user' was deleted successfully from $server" | |
else | |
echo "Error deleting user '$user' from $server" | |
fi | |
done |
The first line of the script, "#!/bin/bash", is known as the shebang line and it tells the operating system that this script should be executed using the bash interpreter.
The next line, "file=iplist.txt", defines a variable called "file" and assigns the value "iplist.txt" to it. This variable is used to store the name of the text file that contains the IP addresses of the remote servers.
The following line, "user=username", defines a variable called "user" and assigns the value "username" to it. This variable is used to store the name of the user that is to be deleted from the remote servers.
The script then uses a "for" loop to iterate through the IP addresses in the "iplist.txt" file. The "for" loop is a powerful feature in bash that allows you to perform a set of commands on each item in a list.
For each IP address in the list, the script uses the "ssh" command to connect to the remote server and execute the command "userdel $user | rm -rvf /home/$user". This command is used to delete the user and remove the user's home directory. The "userdel" command is used to delete a user account and the "rm" command is used to remove a file or directory.
After the user is deleted, the script checks the exit status of the previous command using the "if" statement. If the exit status is 0, it means that the user was deleted successfully and the script prints a message saying "User '$user' was deleted successfully from $server". If the exit status is not 0, it means that there was an error deleting the user and the script prints a message saying "Error deleting user '$user' from $server".
In summary, this script is a simple yet powerful tool that can be used to automate the task of deleting a specific user from a list of remote servers. By using bash scripting and the "for" loop, the script can iterate through a list of IP addresses and perform the same task on each server. The script also uses the "if" statement to check the exit status of the previous command and provide feedback on the success or failure of the task.
Please do check this bash script on my github. And give me a star.😊