During operation and maintenance, sometimes it is necessary to copy a file in batches to multiple Linux servers. If you manually copy one by one, the efficiency is relatively low. In order to improve the efficiency of operation and maintenance, you can use scripts to copy files from one Linux host to multiple servers in batches. The implementation steps are as follows.
One, Linux host settings ssh password-free login
First, the Linux host must be set up for ssh secret-free login. One of them can be used as a trusted host to log in to all other hosts without secret. For the specific configuration method, see " Configuring the trust relationship between two Linux hosts (and how to cancel) ".
Two, create a host list file hosts
The vi hosts command creates a host list file hosts and lists all remote hosts in the file.
$ vi hosts
$ cat hosts
101.132.242.27
47.103.217.188
Three, create a script file remotecopy.sh
#!/bin/bash
while getopts f: OPT;
do
case $OPT in
f|+f)
files="$OPTARG $files"
;;
*)
echo "usage: `basename $0` [-f hostfile] <from> <to>"
exit 2
esac
done
shift `expr $OPTIND - 1`
if [ "" = "$files" ];
then
echo "usage: `basename $0` [-f hostfile] <from> <to>"
exit
fi
for file in $files
do
if [ ! -f "$file" ];
then
echo "no hostlist file:$file"
exit
fi
hosts="$hosts `cat $file`"
done
for host in $hosts;
do
echo "scp $1 $2@$host:$3"
scp $1 $2@$host:$3
done
Fourth, add execution permissions to the script file remotecopy.sh
$ chmod u+x remotecopy.sh
5. Run script commands on trusted hosts
The format of the script running command is as follows:
./remotecopy.sh -f hosts [yourfile] [username] [remotepath]
Note: Parameter 1 [yourfile] is the file to be copied on the trusted host; parameter 2 [username] is the login user; parameter 3 [remotepath] is the file path of the remote host.
Examples are as follows:
$ ./remotecopy.sh -f hosts test.log testuser /home/testuser/
You can copy the file test.log in the current path to the /home/testuser/ directory of other hosts in batches to avoid the secret login user testuser.
If you need to copy folders in batches, simply modify the scp command in the remotecopy.sh file.
Article reference: How
to copy files from one linux machine to multiple