您的位置:首页 > 其它

主机间信任关系建立之ssh+sshpass批量化部署

2016-07-19 13:11 453 查看
ssh通过公钥实现身份认证,可以手工创建.ssh目录并将公钥拷贝至远程主机。
也可通过ssh-copy-id命令将公钥传递至远程主机。
对于批量化部署:
1首先要解决的是身份认证的问题(root密码应该统一)。
2然后通过sshpass的-p密码或-f指定密码文件的方式来传递密码,实现认证登录。
3通过sshpass配合ssh-copy-id命令执行公钥传递

脚本实现公钥的批量分发:
1 sshpass的安装
下载sshpass-1.06
解压并安装
tar zxvf sshpass-1.06
./configure
make&&make install

2脚本
#!/bin/bash

. /etc/init.d/functions

usage () {
if [ ! $# -eq 2 ];then
echo "Usage:/bin/sh $0 -f host_list_file"
exit 0
fi
}

auth () {
ID=`id|awk -F"[=()]+" '{print$2}'`
if [ $ID -ne 0 ];then
echo "This tool should be running under root. Exit."
exit 0
fi
}

pubkey () {
#Create ssh_key
if [ ! -f ~/.ssh/id_dsa ];then
echo "The ssh key is not exist. It will be created..."
echo -e "\n"|ssh-keygen -t dsa -N "" >/dev/null2>&1
echo "The key is created successful."
fi

#Disable StrictHostKeyChecking
grep "^StrictHostKeyChecking no"/etc/ssh/ssh_config >/dev/null 2>&1
if [ $? -ne 0 ];then
echo "StrictHostKeyChecking no" >> /etc/ssh/ssh_config&>/dev/null
fi
}

deploy () {
#input root and password
echo "Deploying pub key."
read -p "Please type the remoteaccount:" ac
read -s -p "Please type the remotepassword:" pw
echo

#Deploy pub key
if [ -f $Hosts ];then
forn in `cat $Hosts`
do
sshpass -p $pw ssh-copy-id -i .ssh/id_dsa.pub $ac@$n &>/dev/null
if [ $? -eq 0 ];then
action "Deploying pub_key for $n......Success!" /bin/true
else
action "Deploying pub_key for $n......Failed!" /bin/false
fi
done
else
exit 0
fi
}

usage $1 $2
Hosts="$2"

auth
pubkey
deploy

3测试
创建主机列表文件hosts
cat /root/hosts
192.168.1.104
192.168.1.105

执行脚本sh deploy_pubkey.sh -f host




然后就可以通过ssh/sshpass/pssh等工具进行远程管理了。

本文出自 “Clark的运维” 博客,请务必保留此出处http://szcat.blog.51cto.com/665775/1827713
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: