了解最新公司動態及行業資訊
背景
在運維或者日常工作生活中,我們經常將一個文件拷貝到其他服務器,或者同時分發到多臺服務器,甚至要求目標機器把文件放在同一個路徑下服務器運維,方便的程序可以進一步調用。
遇到這些問題,我們一般的做法是使用scp或者rsync命令將文件一個一個拷貝到多臺服務器上,費力又費力;大師的方法是用它來完成工作服務器運維,前提是你有技能;快速的方法是使用明天的腳本。
功效展示
目前有4臺機器,分別是node1、node2和node3,可以完成與其他3臺機器的ssh鏈接。/root/test 目錄下有兩個文件 a.txt 和 b.txt。
[root@client test]# ls /root/test/
a.txt b.txt
[root@client test]#
我將文件分發到 node1、node2 和 node3 的 /root/test 并執行以下命令:
# 在/root/test目錄下執行, xrsync是我的腳本
[root@client test]# xrsync a.txt b.txt
執行分發過程:
[root@client test]# xrsync a.txt b.txt
============ node1 ============
sending incremental file list
a.txt
sent 93 bytes received 35 bytes 256.00 bytes/sec
total size is 2 speedup is 0.02
sending incremental file list
b.txt
sent 93 bytes received 35 bytes 85.33 bytes/sec
total size is 2 speedup is 0.02
============ node2 ============
sending incremental file list
a.txt
sent 93 bytes received 35 bytes 256.00 bytes/sec
total size is 2 speedup is 0.02
sending incremental file list
b.txt
sent 93 bytes received 35 bytes 256.00 bytes/sec
total size is 2 speedup is 0.02
============ node3 ============
sending incremental file list
a.txt
sent 93 bytes received 35 bytes 85.33 bytes/sec
total size is 2 speedup is 0.02
sending incremental file list
b.txt
sent 93 bytes received 35 bytes 256.00 bytes/sec
total size is 2 spee
去node2看看,文件確實存在。同樣,node3 和 node4 也是同步的。
# node2上查看
[root@node2 ~]# ls /root/test/
a.txt b.txt
[root@node2 ~]#
# node3上查看
[root@node3 ~]# ls /root/test/
a.txt b.txt
[root@node3 ~]#
# node4上查看
[root@node4 ~]# ls /root/test/
a.txt b.txt
[root@node4 ~]#
腳本
整個腳本的代碼,只需要將改成自己環境的或者ip地址即可。
#!/bin/bash
# 判斷參數是否足夠
if [ $# -lt 1 ]
then
echo Not Enounh Arguement!
exit;
fi
# 遍歷所有的機器
for host in node1 node2 node3
do
echo ============ $host ============
for file in $@
do
# 判斷文件是否存在
if [ -e $file ]
then
# 獲取父目錄
pdir=$(cd -P $(dirname $file); pwd)
# 獲取當前目錄的名稱
fname=$(basename $file)
ssh $host "mkdir -p $pdir"
rsync -av $pdir/$fname $host:$pdir
else
echo $file does not exists!
fi
done
done
運行條件
為了更方便地運行腳本,建議使用以下優化。
1.修改/etc/hosts文件,添加IP地址和主機名的對應關系,這樣我們就可以直接使用主機名進行操作了。例如我演示的機器配置。
vim /etc/hosts
# 加入配置,自己的機器對應修改
……
192.168.31.47 client
192.168.31.48 node1
192.168.31.50 node2
192.168.31.51 node3
2.客戶端機器和目標機器之間使用ssh密碼驗證登錄,這樣傳輸文件時不需要二次驗證。
# 生成ssh私鑰
ssh-keygen -f /root/.ssh/id_rsa -N ''
# 循環把公鑰傳遞到服務器上,免密登錄
for i in node1 node2 node3
do
ssh-copy-id $i
done
# 根據提示輸入密碼
3.為腳本添加可執行權限,并配置環境變量使用全局可用。
# 把文件存儲為xrsync,加上x權限
[root@client shell]# chmod +x xrsync
[root@client shell]#
# 配置環境變量
# 我把腳本放在/opt/shell下的,自己情況類比修改
[root@client shell]# vim /etc/profile.d/my_env.sh
export PATH=$PATH:/opt/shell
# 配置生效,就可以在全局生效了
[root@client opt]# source /etc/profile
至此,早點完成工作,開始愉快的玩耍吧~