0

Here is the body of the script I am running...

for i in `cat ${hostfile}`
        do
        echo "Adding user $username on $i"
        ssh -q $i /usr/bin/sudo /usr/sbin/adduser $username --gecos "$username,,," --disabled-password;
        echo "$username:$password" | /usr/bin/sudo chpasswd;
        /usr/bin/sudo mkdir -p /home/$username/.ssh;
        /usr/bin/sudo touch /home/$username/.ssh/authorized_keys;
        /usr/bin/sudo chmod 600 /home/$username/.ssh/authorized_keys;
        /usr/bin/sudo chmod 700 /home/$username/.ssh;
        /usr/bin/sudo chown -R $username:$username /home/$username
        #ssh -q $i /usr/bin/sudo /usr/sbin/adduser $username --gecos "$username,,," --disabled-password; sudo echo $username:'$password' | chpasswd; /usr/bin/sudo mkdir /home/$username/.ssh; /usr/bin/sudo touch /home/$username/.ssh/authorized_keys; /usr/bin/sudo chmod 600 /home/$username/.ssh/authorized_keys; /usr/bin/sudo chmod 700 /home/$username/.ssh; /usr/bin/sudo chown -R $username:$username /home/$username; adduser $username $group
done

It executes but does not create the .ssh directory.

Kulfy
  • 17,696
smars
  • 1
  • Are the lines starting with echo supposed to be run locally? What is the use of ; at the end of lines? – FedKad May 16 '19 at 18:59
  • As a general rule, it is safer to avoid for i in $(cat file) and use while IFS= read -r file; do ...; done < file which also avoids the unnecessary use of cat. See https://mywiki.wooledge.org/DontReadLinesWithFor. Granted, this shouldn't be an issue if your file is just a list of host names, but it's better to not get into this habit. – terdon May 16 '19 at 19:30

1 Answers1

0

Your script is only running one command on the remote server:

ssh -q $i /usr/bin/sudo /usr/sbin/adduser $username --gecos "$username,,," --disabled-password;

Everything after that is run on your local machine instead. If you want to run multiple commands on the same ssh session, you need to pass them to ssh as a single command. For example:

while IFS= read -r  host; do
    echo "Adding user $username on $i"
    ssh -q "$host" "/usr/bin/sudo /usr/sbin/adduser '$username' --gecos '$username,,,' --disabled-password; \
    echo '$username:$password' | /usr/bin/sudo chpasswd; \
    /usr/bin/sudo mkdir -p /home/'$username'/.ssh; \
    /usr/bin/sudo touch /home/'$username'/.ssh/authorized_keys; \
    /usr/bin/sudo chmod 600 /home/'$username'/.ssh/authorized_keys; \
    /usr/bin/sudo chmod 700 /home/'$username'/.ssh; \
    /usr/bin/sudo chown -R '$username:$username' /home/'$username'"           
done < "$hostfile"

Note how all the commands are within the same " " quoted block. The \ at the end of the line is just for clarity: they let you add the next command on a separate line.

terdon
  • 100,812