Using BASH script to Copy Files/Folders to Multiple Remote Servers


I have quite a few servers, and deploying same files/folders to them is a problem. Then I come up with the following BASH script where I can just run on the master server and it will upload the files or folders to all other slave servers.

In order to avoid entering username/password everytime, we have to put the SSH keys to the ~/.ssh/authorized_keys.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
 
hosts=( "host1" "host2" )
port=12345
user=root
 
sync() {
    echo scp -r -P $port $2 $user@$1:$3
    scp -r -P $port $2 $user@$1:$3
}
 
if [ -z "$1" ] || [ -z "$2" ] 
then
    echo "Syntax $0 file remote_path"
    exit 1
fi
 
for i in "${hosts[@]}"
do
    sync $i $1 $2
done
#!/bin/bash

hosts=( "host1" "host2" )
port=12345
user=root

sync() {
    echo scp -r -P $port $2 $user@$1:$3
    scp -r -P $port $2 $user@$1:$3
}

if [ -z "$1" ] || [ -z "$2" ] 
then
    echo "Syntax $0 file remote_path"
    exit 1
fi

for i in "${hosts[@]}"
do
    sync $i $1 $2
done

Example usage:

1
$./sync /local_files/data.txt /remote_dir/
$./sync /local_files/data.txt /remote_dir/

It will copy the local file to the remote_dir of all remote hosts. It is based on scp command.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
207 words
Last Post: Teaching Kids Programming - Escape Maze by Breadth First Search Algorithm
Next Post: Teaching Kids Programming - Depth First Search Algorithm to Convert to Elephant Binary Tree

The Permanent URL is: Using BASH script to Copy Files/Folders to Multiple Remote Servers

Leave a Reply