Run one script in multiple servers
We will use 3 files to run a single script into multiple server at once.
- script.sh
- servers.list
- run.sh
The file servers.list is a list of all servers you will run the script on.
The file script.sh is the script that will be runned on the servers.
The file run.sh will get all servers into the file serves.list will copy the script.sh to /tmp of each server and execute from the server.
Files
servers.list
server1 server2 server3 . . .
script.sh
#!/bin/bash echo "Hello from $(hostname)"
run.sh
#!/bin/bash
username=USER_USERNAME
password=USER_PASSWORD
list=`cat servers.list`
pack=script.sh
for server in $list; do
echo ""
echo $server
scp_command="sshpass -p "$password" scp -o StrictHostKeyChecking=no -o NumberOfPasswordPrompts=1 -o ConnectTimeout=10 -q $pack $username@$server:/tmp"
$scp_command
ssh_command="sshpass -p "$password" ssh -o StrictHostKeyChecking=no -o NumberOfPasswordPrompts=1 -o ConnectTimeout=10 -q $username@$server"
# running without sudo
$ssh_command chmod +x /tmp/script.sh
$ssh_command /bin/sh /tmp/script.sh
$ssh_command rm -fr /tmp/script.sh
# running with sudo
#$ssh_command chmod +x /tmp/script.sh
#$ssh_command sudo /bin/sh /tmp/script.sh
#$ssh_command sudo rm -fr /tmp/script.sh
done
Remember that if you want to run the script with sudo on the servers just uncomment what is bellow the "# running with sudo" and comment what is bellow "# running without sudo".