Using while loop to ssh to multiple servers and execute commands

Gloria Palma González
1 min readFeb 11, 2020

--

it’s a short post because is more like a note for me and of course for help.

This is a trick for saving time when you don't have other tools like an Ansible, for example, u_u ( i will cry)

For example, in this case I want to set the hostname by host then I created a file server.txt and execute while in a line.

server.txt contains all the hostname, for example:

worker-1.example.com
worker-2.example.com
worker-3.example.com
worker-4.example.com
worker-5.example.com
worker-6.example.com
worker-7.example.com
worker-8.example.com
worker-9.example.com

My while in a line:

while read HOST ; do ssh $HOST “hostnamectl set-hostname $HOST” < /dev/null; done < servers.txt

And this is all, you can change hostnamectl set-hostname for another command if you needed.

Bye :)

--

--

Gloria Palma González
Gloria Palma González

Written by Gloria Palma González

My life is a paradigm: I can do anything. IT engineer, melomaniac, in love: #Infrastructure #OpenSource #CommunityLeadershipTeams #SoftwareEngineering

No responses yet