在运维时,有时需要将一个文件批量拷贝到多台 Linux 服务器上。如果人工逐台拷贝,效率比较低下。为提高运维效率,可以通过脚本实现将文件从一台 Linux 主机批量拷贝到多台服务器,实现步骤如下所示。
首先 Linux 主机必须设置了 ssh 免密登录,可以将其中一台作为信任主机,免密登录到其他所有主机,具体配置方法见《两台 Linux 主机之间配置信任关系(以及如何解除)》。
vi hosts 命令创建主机列表文件 hosts,将所有远程主机列在文件中。
$ vi hosts
$ cat hosts
101.132.242.27
47.103.217.18812345
#!/bin/bashwhile 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>"
exitfi
for file in $filesdo
if [ ! -f "$file" ];
then echo "no hostlist file:$file"
exitfi
hosts="$hosts `cat $file`"
done
for host in $hosts;
do
echo "scp $1 $2@$host:$3"
scp $1 $2@$host:$3done1234567891011121314151617181920212223242526272829303132333435
$ chmod u+x remotecopy.sh1
脚本运行命令格式如下:
./remotecopy.sh -f hosts [yourfile] [username] [remotepath] 1
备注:参数1 [yourfile] 为信任主机上待拷贝的文件;参数2 [username]为登录用户;参数3 [remotepath] 为远程主机文件路径。
示例如下:
$ ./remotecopy.sh -f hosts test.log testuser /home/testuser/1
就可以将当前路径下的文件 test.log 以免密登录用户 testuser 远程批量拷贝到其它主机的 /home/testuser/ 目录下了。
若需要批量复制文件夹,只需简单修改 remotecopy.sh 文件中的 scp 命令即可。
文章参考:
将文件从一台linux机器拷贝到多台的方法
苏公网安备 32132202001088号
| Copyright 北极熊 北格技术 版权所有