shell+expect建立多個節點無密碼ssh

liwl1991發表於2024-11-02
#!/bin/bash
password="liwanliang"
#1.
echo "為每個節點建立公金鑰對..."
for node in node{061..065}
do
    echo "${node}開始操作"
    expect -c "
            set timeout 1
            log_user 0
            spawn ssh root@${node}
            expect {
                    \"*yes/no*\" { send \"yes\r\"; exp_continue }
                    \"*password:*\" { send \"${password}\r\"; exp_continue }
            }
            expect \"\#\"
            send \"ssh-keygen -t rsa -f ~/.ssh/id_rsa -P \'\'\r\"
            expect \"\# \"
            send \"exit\r\"
            log_user 1
    "
    echo "${node}操作成功!"
done

#2. 
echo "複製所有節點的公鑰到本地的一個檔案"

for node in node{061..065}
do
    echo "${node}開始操作"
    expect -c "
        log_user 0
        spawn scp root@${node}:/root/.ssh/id_rsa.pub ./${node}.pub
        expect {
            \"*password:\" { send \"${password}\r\"; exp_continue}
        }
        log_user 1
    "
    echo "${node}操作成功"
done

echo "合併公鑰檔案..."
cat *.pub >> authorized_keys

echo "分發公鑰檔案..."

for node in node{061..065}
do
    echo "${node}開始操作"
    expect -c "
        log_user 0
        spawn scp ./authorized_keys root@${node}:/root/.ssh/
        expect {
            \"*password:\" { send \"${password}\r\"; exp_continue}
        }
        spawn ssh root@${node}
        expect \"\# \"
        send \"chmod 600 /root/.ssh/authorized_keys\r\"
        expect \"\# \"
        send \"exit\r\"
        log_user 1
    "
    echo "${node}操作成功"
done

echo "修改authorized_keys許可權..."
for node in node{062..065}
do
    echo "${node}開始操作"
    ssh ${node} chmod 600 /root/.ssh/authorized_keys
    echo "${node}操作成功"
done


echo "分發ssh_config檔案..."

for node in node{062..065}
do
    echo "${node}開始操作"
    scp /etc/ssh/ssh_config root@${node}:/etc/ssh/ssh_config 
    echo "${node}操作成功"
done

echo "刪除pub檔案"
rm -rf *.pub authorized_keys

當節點需要取消ssh登陸一些提示資訊時,修改/etc/ssh/ssh_config,新增

Host *
    SSAPIAuthentication no
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
    LogLevel quiet

上述是讓每個節點都建立自己的公私金鑰對,屬於比較複雜的情況。

如果僅使用同一套,只需要傳輸.ssh,ssh_config檔案就可以了

相關文章