快速做ssh免密钥登陆

1、本地生成密钥并发送目标主机

ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa >/dev/null 2>&1 #采用数字签名RSA或DSA生成密钥文件和私钥文件 id_rsa,id_rsa.pub或id_dsa,id_dsa.pub
ssh-copy-id -i /root/.ssh/id_dsa.pub root@10.10.16.224   #默认以22端口的方式将.pub文件复制到B机器的.ssh目录, 并cat id_dsa.pub >> ~/.ssh/authorized_keys
ssh-copy-id -i /root/.ssh/id_dsa.pub "-p 1022 root@10.10.16.224" #以1022端口的方式将.pub文件复制到B机器的.ssh目录

2、写成脚本

#!/bin/bash
Port="10086"
User="root"
Pwd="xxxxxx"
function YUM_make(){
   echo "正在安装epel源yum仓库,请稍后..."
   cd /etc/yum.repos.d/ &&\
   [ -d bak ] || mkdir bak
   [ `find ./*.* -type f | wc -l` -gt 0 ] && find ./*.* -type f |  xargs -i mv {} bak/
   #wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo &>/dev/null
   wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
   yum -y clean all &>/dev/null
   yum makecache &>/dev/null
}
echo "正在进行网络连接测试,请稍后..."
      ping www.baidu.com -c2 >/dev/null ||(echo "无法连接外网,请检查网络环境!" && exit)
    #[ $# -eq 0 ] && echo "没有参数!格式为:sh $0 参数10.10.16.n" && exit 
   rpm -q sshpass &>/dev/null || yum -y install sshpass #&>/dev/null
   sleep 1;
   rpm -q sshpass &>/dev/null
    if [ $? -ne 0 ];then
       #YUM_make
       yum -y install sshpass &>/dev/null || (echo "sshpass yum error!" && exit)
    fi
echo "正在创建密钥对...."
[ -d ~/.ssh ] || mkdir ~/.ssh;chmod 700 ~/.ssh
rm -f ~/.ssh/id_dsa ~/.ssh/id_dsa.pub
ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa >/dev/null 2>&1
for ip in `cat host.txt`
do
    ping $ip -c1 &>/dev/null
    if [ $? -gt 0 ];then
        echo "$ip无法ping通请检查网络" 
        continue
    fi
    sshpass -p "$Pwd" ssh-copy-id -i ~/.ssh/id_dsa.pub -o StrictHostKeyChecking=no -p$Port ${User}@$ip  &>/dev/null
    echo "$ip 密钥分发成功"
done
##the next step is use ansible & change /etc/ansible/host
View Code

  普通用户登录出现-bash-4.2$ 解决方法:

cp /etc/skel/.bashrc ./
cp /etc/skel/.bash_profile ./
View Code
posted @ 2018-08-28 17:40  淺景尘  阅读(228)  评论(0编辑  收藏  举报
TOP