SSH 免密码登陆

1.在A机生成公钥和私钥

ssh-keygen -t rsa –P
一般采用的ssh的rsa密钥:
id_rsa     私钥
id_rsa.pub 公钥
下述命令产生不同类型的密钥
ssh-keygen -t dsa

 

2.把A机下的/root/.ssh/id_rsa.pub 复制到B机的 /root/.ssh/authorized_keys文件里,先要在B机上创建好 /$HOME/.ssh 这个目录,用scp复制。

scp XXX@192.168.1.12:/$HOME/.ssh/id_rsa.pub  $HOME/.ssh/
cat id_rsa.pub  >>$HOME/.ssh/authorized_keys
chmod 600  $HOME/.ssh/authorized_keys

3.如果要互相免密码登陆,则需要在将B机的公钥拷贝到A机上。

4.执行脚本

sudo yum install expect.



function settingSShNoLogin(){
   echo "setting ssh no login"
      pwd="\r"
      keyGen="ssh-keygen -t rsa -f $HOME/.ssh/id_rsa"
      chmod="chmod g-w  $HOME/.ssh/authorized_keys"
    machinedPwd="*****"
   echo "step 1->setting private key"
     $keyGen 
     echo "step 2->chmod for public key"
        if [ ! -f "$HOME/.ssh/authorized_keys" ];then
          cat > $HOME/.ssh/authorized_keys
       fi
         cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
         $chmod
    echo "step 3->merge authorized_keys file"
          OLD_IFS="$IFS"
            IFS=","
            nodeHosts=($NODE_HOSTS)
            IFS="$OLD_IFS"
            
           for  node in ${nodeHosts[@]}
              do
          if [  "$node" != "$machine_name" ]; then
           expect -c "set timeout -1;
                spawn ssh-copy-id -i $HOME/.ssh/id_rsa.pub conversant@$node;
                expect {
                    *(yes/no)* {send -- yes\r;exp_continue;}
                    *assword:* {send -- $machinedPwd\r;exp_continue;}
                    eof        {exit 0;}
                }";
          fi
           done
}
posted @ 2015-12-16 17:49  lily-tiantian  阅读(168)  评论(0编辑  收藏  举报