59. 脚本:ssh免密批量分发文件
7. ssh免密钥批量分发文件专业脚本¶
有3台机器(m01,backup,nfs01),采用ssh免密钥实现从m01到其他两台机器无密码登录后,请写脚本实现从m01批量分发任意文件到其他两台机器的任意目录下
思路分析
1.生成密钥
ssh-keygen
2.分发密钥
ssh-copy-id -i id_rsa.pub 10.0.0.8
ssh-copy-id -i id_rsa.pub 10.0.0.41
3.测试
ssh 10.0.0.8 free -m
ssh 10.0.0.41 free -m
测试脚本
vim ssh_test.sh
#!/bin/bash
if [ $# -ne 1 ];then
echo "usage: $0 cmd"
exit 1
fi
for n in 8 41
do
echo "-----------10.0.0.$n--------------"
ssh 10.0.0.$n $1
done
bash ssh_test.sh "df -h"
分发文件脚本
#!/bin/bash
for n in 8 41
do
echo "-----------10.0.0.$n---------"
scp -rp /oldboy 10.0.0.$n:/opt
done
改造
#!/bin/bash
if [ $# -ne 2 ];then
echo "usage:$0 localdir remotedir"
exit 1
fi
for n in 8 41
do
echo "-----10.0.0.$n--------"
scp -rp $1 10.0.0.$n:$2
done
优化
#!/bin/bash
. /etc/init.d/functions
if [ $# -ne 2 ];then
echo "usage:$0 localdir remotedir"
exit 1
fi
for n in 8 41 42 43
do
scp -rp $1 10.0.0.$n:$2 &>/dev/null
if [ $? -eq 0 ];then
action "10.0.0.$n is ok" /bin/true
else
action "10.0.0.$n is fail" /bin/false
fi
done
最后更新:
2022-02-19 13:59:07