centos7 ssh免密登录(shell脚本)

/ 技术分享 / 没有评论 / 1573浏览

centos7 ssh免密登录(shell脚本)

环境(centos7)

hostnameip
node192.168.100.199
node1192.168.100.101
node2192.168.100.102

1.分别修改主机名

hostnamectl set-hostname <hostname>

2.分别修改hosts

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.100.199 node
192.168.100.101 node1
192.168.100.102 node2

3.在node上执行下面的脚本

#!/bin/bash
yum -y install expect
#PWD登录密码
PWD=111111
ips=$(cat /etc/hosts |grep -v "::" | grep -v "127.0.0.1")
key_generate() {
    expect -c "set timeout -1;
        spawn ssh-keygen -t rsa;
        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_rsa.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
key_generate
for ip in $ips
do
    auto_ssh_copy_id $ip  $PWD
done

4. 然后node就可以免密登录到其他节点

PS. 手动设置免密登录需要用到的命令

ssh-keygen -t rsa -P ""
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys