I have a list of around 100 servers that I need to add a user to. I have an ssh-rsa key I also need to add to the authorized keys file. I'm trying to accomplish this using a for loop but I'm not getting anywhere.

I use an alias to SSH to bastion (connect), and I can connect to the server but it halts at the prompt, then it won't continue on until I type exit at said prompt. Even then I think it's actually just executing the commands locally rather than remote.

I'm not able to use any third party tools so I have to use what's available in a default installation.


connect='ssh user@bastionserver -t --'
adduser='adduser  -disabled-password  --gecos "a user account" -home /home/foobar foobar -q'
mkdir='mkdir /home/foobar/.ssh'
chmod='chmod -R 700 /home/foobar/.ssh/'
chown='chown -R soc /home/foobar/'

for server in $(cat server_list.txt)
    $connect root@"$server"
    echo "$adduser"
    echo "$mkdir"
    echo "$chmod"
    echo "$chown"

I can't figure this out! Any help appreciated.


1 Answer 1


The ssh command can take a command to run on the remote server. When given no command to run, it starts an interactive shell. Use ssh to execute the commands that you'd like to execute. For example:


while read server; do
    ssh "user@$server" sh -c '
        adduser  -disabled-password  --gecos "a user account" -home /home/foobar foobar -q
        mkdir /home/foobar/.ssh
        chmod -R 700 /home/foobar/.ssh/
        chown -R soc /home/foobar/'
done <server_list.txt

This is obviously untested code. To be able to execute more than one command, we start a child shell using sh -c and give that shell a list of commands to run.

Your command "halts" because it connects to the server (actually, to user@bastionserver, but I don't know how this server relates to the servers listed in the input file) and starts an interactive shell. Your script will not continue until this interactive shell exits.

The rest of your code just outputs strings to the terminal. It does not execute them.

Don't try to put commands in variables. It very seldom works as expected. See e.g. "How can we run a command stored in a variable?".

If this was a real work task for me, I would probably try to do it using something like Ansible. Unfortunately, I don't know Ansible well enough to confidently give a complete solution using it here.

  • @ilkkachu Or one could transfer a small script over with scp and then execute that with ssh. Or just use something like Ansible, which is made for these kinds of operations.
    – Kusalananda
    Commented Jun 5, 2018 at 15:04
  • @ilkkachu Fair enough.
    – Kusalananda
    Commented Jun 5, 2018 at 15:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .