Using scp
to copy a file from the local-host to a remote-host goes like this:
scp file username@remote-host:/remote/directory/
Where file
is the local file you want to copy to the remote host, username
is a valid username on the remote host, remote-host
is the actual address/IP of the remote host and /remote/directory/
is the full path of the destination directory on the remote host ... You'll need to enter a password every time you copy a file to a remote host unless you set a password-less "SSH Key Authentication".
To achieve what you want you will need to prepare and test three scp
commands(One for each remote server) like so:
scp file username@Host-B:/remote/directory/
scp file username@Host-C:/remote/directory/
scp file username@Host-D:/remote/directory/
These three command lines are examples using scp
which should work fine for your use case but you can use any other tool like e.g. rsync
.
Note that scp
and other remote file copying utilities are prone to failure due to bad/dropping connection to the remote server ... So I would advise also to check the exit status of scp
(It exits 0
on success and >0
otherwise) with e.g. until [ "$s" = 0 ]; do ... done
where $s
will hold the exit status of the lastly executed scp
command so that if that command did not succeed in copying the file to one of the remote servers then the script will attempt to copy that file to the next server ensuring all files are copied to working servers even if one or more of them has connection issues.
Then use them in a for loop while alternating between them like so:
#!/bin/bash
# This script should be run on Server-A
i=1
for f in /opt/Test/*; do
s=1
until [ "$s" = 0 ]; do
if [ "$i" = 1 ]; then
scp "$f" username@Host-B:/remote/directory/
s="$?"
i=2
elif [ "$i" = 2 ]; then
scp "$f" username@Host-C:/remote/directory/
s="$?"
i=3
elif [ "$i" = 3 ]; then
scp "$f" username@Host-D:/remote/directory/
s="$?"
i=1
fi
done
done
Alternatively, consider mounting remote directories from server-B, server-C and server-D as local shares on server-A and copy to them locally with e.g. just cp
if this is an option as this would be more efficient and much faster ... Assuming you mount those on mount-points e.g. /mnt/B/
, /mnt/C/
and /mnt/D/
then the script would need to be modified to use cp
like so:
#!/bin/bash
# This script should be run on Server-A
i=1
for f in /opt/Test/*; do
s=1
until [ "$s" = 0 ]; do
if [ "$i" = 1 ]; then
cp -- "$f" /mnt/B/
s="$?"
i=2
elif [ "$i" = 2 ]; then
cp -- "$f" /mnt/C/
s="$?"
i=3
elif [ "$i" = 3 ]; then
cp -- "$f" /mnt/D/
s="$?"
i=1
fi
done
done