批量部署ssh私钥认证
使用密钥登陆时,避免每次要手动指定密钥文件
# ~/.ssh/config 文件示例 # Host 参数标明以下内容仅适用于访问 236 主机时适用,Host 参数本身只是一个入口字符串; Host 192.168.99.236 HostName wjoyxt-666 User wjoyxt Port 22 IdentityFile ~/.ssh/wjoyxt.pem
Host 192.168.99.237
HostName wjoyxt-888
User wjoyxt
Port 22
IdentityFile ~/.ssh/wjoyxt.pem
chmod 600 ~/.ssh/wjoyxt.pem ~/.ssh/config
避免首次ssh远程登陆时输入yes
方法一:ssh -o stricthostkeychecking=no 172.17.213.213
方法二:登录其它服务器避免被询问也可以在/etc/ssh/ssh_config中设置 "StrictHostKeyChecking no",默认是注释掉的 "# StrictHostKeyChecking ask"。修改后不会被询问而直接要求输入密码。
vim batch_sshkey.sh
#!/bin/bash
cd /root
cat /root/.ssh/id_rsa.pub > /root/.ssh/authorized_keys
for i in `cat iplist`
do
ip=$(echo "$i"|cut -f1 -d":")
password=$(echo "$i"|cut -f2 -d":")
expect -c "
spawn scp /root/.ssh/authorized_keys /root/remote_operate.sh root@$ip:/tmp/
expect {
\"*yes/no*\" {send \"yes\r\"; exp_continue}
\"*password*\" {send \"$password\r\"; exp_continue}
\"*Password*\" {send \"$password\r\";}
}
"
expect -c "
spawn ssh root@$ip "/tmp/remote_operate.sh"
expect {
\"*yes/no*\" {send \"yes\r\"; exp_continue}
\"*password*\" {send \"$password\r\"; exp_continue}
\"*Password*\" {send \"$password\r\";}
}
"
done
============================================================
vim iplist(前面是IP,后面是密码,用冒号:分割) 密码后面不允许有空格
192.168.8.23:123456
192.168.8.24:456789
============================================================
vim remote_operate.sh
#!/bin/bash
if [ ! -d /root/.ssh ];then
mkdir /root/.ssh
fi
cp /tmp/authorized_keys /root/.ssh/
rm -f /tmp/authorized_keys
rm -f $0
==========================================================
运行batch_sshkey.sh后即可实现批量部署。
-----------------------------------------------------------------------------------------------------------------------------------------
以上情形适用于超大规模的批量部署,对于十几台机器规模而言的话有点小题大做了,以下示例比较适用于小规模的批量部署:
#!/bin/bash IP_list=10.0.10.60,10.0.10.62 PWD=123456 key_generate() { expect -c "set timeout -1; spawn ssh-keygen -t dsa; expect { {Enter file in which to save the key*} {send -- \r;exp_continue} {Enter passphrase*} {send -- \r;exp_continue} {Enter same passphrase again:} {send -- \r;exp_continue} {Overwrite (y/n)*} {send -- n\r;exp_continue} eof {exit 0;} };" } auto_ssh_copy_id () { expect -c "set timeout -1; spawn ssh-copy-id -i $HOME/.ssh/id_dsa.pub root@$1; expect { {Are you sure you want to continue connecting *} {send -- yes\r;exp_continue;} {*password:} {send -- $2\r;exp_continue;} eof {exit 0;} };" } rm -rf ~/.ssh 2>/dev/null key_generate ips=$(echo $IP_list | tr ',' ' ') for ip in $ips do auto_ssh_copy_id $ip $PWD done eval &(ssh-agent) ssh-add