一台Linux服务器向多台服务器同时上传文件脚本

文章目录
[隐藏]

运维工作中,时常需要向多台服务器上传文件,如果使用FTP等软件上传效率很慢,配置rsync当然可以实现,本文介绍一种更为方便的方法。

我绘制了拓扑图供参考:

一台Linux服务器向多台服务器同时上传文件脚本

本文要实现上图中 server0(服务端) 要向 server1 server2 server3(客户端) 同时传输文件。预设IP地址:

  • server0:192.168.1.10
  • server1:192.168.1.11
  • server2:192.168.1.12
  • server3:192.168.1.13

生成服务器之间密钥

# ssh-keygen //一直回车使用默认值
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
e0:f6:59:eb:f7:a6:e3:2f:16:39:a2:14:61:31:4a:1f root@LinServ-1

ssh-keygen 用于为生成、管理和转换认证密钥,包括 RSA 和 DSA 两种密钥。密钥类型可以用 -t 选项指定。如果没有指定则默认生成用于SSH-2的RSA密钥。

复制密钥文件到远程服务器

ssh-copy-id -i /root/.ssh/id_rsa 192.168.1.11

0
The authenticity of host '192.168.1.11 (192.168.1.11)' can't be established.
RSA key fingerprint is 6e:34:d4:8c:fb:72:72:3a:49:7a:14:23:20:59:ea:28.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.11' (RSA) to the list of known hosts.
root@192.168.1.11's password: (输入192.168.1.11 root密码)
Now try logging into the machine, with "ssh '192.168.2.11'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

ssh-copy-id -i /root/.ssh/id_rsa 192.168.1.12
同上

ssh-copy-id -i /root/.ssh/id_rsa 192.168.1.13
同上

ssh-copy-id 命令可以把本地的ssh公钥文件安装到远程主机对应的账户下。

脚本

#!/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 "do $host"
	scp $1 root@$host:$2
done

将以上脚本内容保存为:remotecopy.sh

创建主机列表文件

vim hostlist

192.168.1.11
192.168.1.12
192.168.1.13

每一行写上一个IP地址后保存。

在服务端 192.168.1.0 执行脚本

./remotecopy.sh -f /usr/local/hostlist /usr/local/test /usr/local/
  • /usr/local/hostlist  主机列表文件路径
  • /usr/local/test  需要传送的文件
  • /usr/local/  传到客户端的位置

6条评论

写评论

您必须登录后才可以发表评论。

本人从事电脑网络维护工作多年,对电脑配置较为熟悉,闲暇之余精心搜罗了目前主流电脑配置清单推荐给大家。紧跟市场动态,定期更新电脑硬件配置方案,扫除一切垃圾坑爹配置,提供最具性价比的电脑配置清单!本站涵盖内容包括:电脑组装机配置单、电脑组装机报价、电脑组装机教程等,另外还提供很多技术文章供您学习!