运维工作中,时常需要向多台服务器上传文件,如果使用FTP等软件上传效率很慢,配置rsync当然可以实现,本文介绍一种更为方便的方法。
我绘制了拓扑图供参考:
本文要实现上图中 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 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/
传到客户端的位置
THE END
暂无评论内容