0

I have 3 remote servers to which I need to copy files from the source server rather than having to run same command multiples times for each server, can it be possible to select one server from the list and then transfer files to that server?

My aim here is to avoid writing same piece of code for each server individually.

Eg:

A = source server
B = remote server 1
C = remote server 2
D = remote server 3
(there may be more remote servers in future)

Enter which server you want the files to be copied to (B/C/D):

if I choose B on command line, following command gets executed:

scp xyz.txt user@remoteserver2:/home 
scp jkl.txt user@remoteserver2:/home

Similarly if other options are chosen, files should get copied to that server.

Here's the code that i have for copying files on 1 server.

#!/bin/sh
today=`date '+%Y%m%d'`;
min_date=`date -d "$today -14days" +%Y%m%d`
max_date=`date -d "$today -1days" +%Y%m%d`
read -p "Enter the date you want input files for [yyyymmdd]: " user_date
udate=$user_date
if [[ $user_date -ge $min_date && $user_date -lt $today ]]
then
  ssh user@server2 mkdir -p /data/${udate}_inputfiles/{f1,f2,f3,f4,f5,f6}
   echo "Starting to copy files"
    cd /homepath1
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f1
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f2
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f3
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f4
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f5
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f6
    
else
    echo "Entered date is invalid: Please specify date between $min_date and $max_date"
fi    
0

1 Answer 1

0

It's simple, write a function:

function serverscp () {
s="$1"
ssh user@$s mkdir -p /data/${udate}_inputfiles/f{1,2,3,4,5,6}
echo "Starting copy"
cd /homepath1
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f1
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f2
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f3
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f4
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f5
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f6
cd $OLDPWD
}

Later in your script,

for tgt in server1 server2 server3 ; do
  serverscp $tgt
done

Warning untested code, not even checked with https://shellcheck.org

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.