Hi Folks,
I have made a bash script which ssh's to a number of servers (IPs are read from a text file) and adds users with a specified username and userid. The user details are also read from a text file. So I am basically running nested for loops (once for Host IP and once for each line in user_list).
The script is working as expected, only letdown being the password prompts. For each IP the password is prompted twice (first time for ssh and second time for sudo).
I would very much like to use an expect script to automate the credentials part. I have no prior experience with expect and I could not find examples of nested loop or string manipulation (when read from a file) in expect.
Here's my working bash script [some details have been omitted]
Code:
#!/bin/bash
SSH_USER="username"
HOST_IPs=/path/to/ip_list
users=/path/to/user_list
for ip in $(cat $HOST_IPs)
do
for i in $(cat $users)
do
#echo $i
USERS=`echo $i|awk -F: '{print $1}'`
USRID=`echo $i|awk -F: '{print $2}'`
#echo $USERS
echo "adding $USERS with ID $USRID to $ip"
ssh $SSH_USER@$ip " sudo /usr/sbin/useradd -M -u $USRID -c 'description' -G secondary_GRP $USERS ;sudo chage -M -1 $USERS "
###
if [ $? -eq 0 ]; then
echo "User $USERS has been created successfully on $ip"
else
echo "Please check the log or verify it manually."
fi
done
done
Could I get some pointers on --
A. How may I use nested for loops in expect ?
B. How may I use string manipulation from file ? [my user details are kept on a text file in USERNAME:USERID format. I would like to know if I may use something like
awk -F: '{print $1/$2}' FILENAME]
C. Is there any way I can call an expect script to this position (
###) and provide the passwords ?
Note:
1. I am not looking for a solution with sshpass /ssh keypair.
2. My environment is a CentOS 6.9 VM. Openssh -> 5.3p1-123.el6_9, bash -> 4.1.2-48.el6, expect -> 5.44.1.15-5.el6_4