This page looks best with JavaScript enabled

How to add user on remote servers using Bash script

 ·  ☕ 2 min read  ·  🐧 sysadmin
  1. Here is a video tutorial

Scripts and configuration files are available here:

  1. Install sshpass

SLES | openSUSE Leap 15.4

1
sudo zypper install sshpass 

Debian

1
sudo apt install sshpass 

Red Hat

1
sudo dnf install sshpass 
  1. Create a file
1
vim pass_file

and place a password for the user that is currently able to connect to remote hosts.

  1. Make the script read only for this user
1
chmod 400 pass_file
  1. Create a list of servers with IP addresses or hostnames
1
vim servers
  1. Create a script
1
vim  adduser.sh

And add the below content

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/bin/bash
servers=$(cat servers)
echo -n "Enter the username: "
read userName
echo -n "Enter the user uid: "
read userUID
echo -n "Enter the password: "
read -s passwd
clear
for i in $servers; do
  sshpass -f pass_file ssh -q -t $USER@$i "hostname; sudo useradd -m -u $userUID $userName -d /home/$userName -s /bin/bash && echo '$userName:$passwd' | sudo chpasswd"
  if [ $? -eq 0 ]; then
    echo "User '$userName' added on '$i'" || echo "User '$userName' already exists on '$i'"
  else
    echo "Error on $i"
  fi
done
echo
read -n1 -s -p "Checking? (y)es or (n)o " ans
echo
if [ $ans == 'y' ] ;then
  for i in $servers; do 
    sshpass -f pass_file ssh -q -t $USER@$i "hostname; id $userName"
  done
fi
  1. Make sure that PasswordAuthentication has set boolean value to yes in /etc/ssh/sshd_config file on remote servers

  2. Make the script executable

1
chmod +x adduser.sh
  1. Execute the script
1
./adduser.sh
  1. Provide username: ansible, UID and password.
Share on

sysadmin
WRITTEN BY
sysadmin
QA & Linux Specialist