规划如下的四台主机:
web1:192.168.3.109
web2:192.168.3.103
web3.192.168.3.108
proxy:192.168.3.101
在proxy主机上做好免密登录所有主机。在proxy主机的/etc/hosts文件内编写以下内容:
192.168.3.101 proxy
192.168.3.109 web1
192.168.3.103 web2
192.168.3.108 web3
编写以下脚本copy-file.sh实现功能:复制本地主机下某一文件到在一个文件中指定的远程主机的相同目录中,如果远程主机中此目录不存在,则先创建这个目录,然后再进行复制。注意:四台主机需要存在相同用户名的用户,此处都是使用root用户。
[root@proxy ~]# cat copy-file.sh
#!/usr/bin/bash
# copy a file of localhost to the same path of remote hosts which are in the designate file
# Usage: copy-file <filename> <file>
if [ $# -ne 2 ];then
echo "Usage: copy-file <filename> <file>"
exit 1
fi
FILENAME=$1
FILE=$2
if [ ! -e ${FILENAME} -o ! -f ${FILENAME} ];then
echo "the file[${FILENAME}] for copying not exists or not a ordinary file!"
exit 1
fi
if [ ! -e ${FILE} -o ! -f ${FILE} ];then
echo "the file[${FILE} for designating the hosts not exists or not a ordinary file!]"
exit 1
fi
HOSTS=$(cat ${FILE})
IP=
for host in ${HOSTS}
do
ping -c3 -W1 -i1 $host &>/dev/null
if [ $? -eq 0 ];then
echo "$host is on line!"
IP="${IP} ${host}"
else
echo "$host is offline!"
fi
done
if [[ "${FILENAME}" =~ ^\/ ]];then
echo "absolute path: ${FILENAME}"
DIR=$(dirname ${FILENAME})
FILENAME=$(basename ${FILENAME})
else
echo "relative path: ${FILENAME}"
ABS="$(pwd)/${FILENAME}"
DIR=$(dirname ${ABS})
FILENAME=$(basename ${ABS})
fi
echo "copy file ${FILENAME} in ${DIR} to the ${DIR} of ${IP}"
for host in $IP
do
ssh ${USER}@${host} "[ ! -d ${DIR} ] && mkdir -p ${DIR}" &>/dev/null
scp ${DIR}/${FILENAME} ${USER}@${host}:${DIR} &>/dev/null
if [ $? -eq 0 ];then
echo "copy ${FILENAME} to ${host} successfully!"
else
echo "copy ${FILENAME} to ${host} failed!"
fi
done
copy-file.sh放在/root目录下,赋予其执行权限,在/root下创建一个内容为hello world的a/b/c.txt文件,再创建一个hosts.txt文件,其内容为:
执行./copy-file.sh a/b/c.txt hosts.txt,结果如下:
到web1 web2 web3主机上的/root下查看,可以看到它们在/root下多一个a/b路径,在此路径下多了一个c.txt文件。
web1:
web2:
web3: