自動ssh免密配置腳本


因為調用ssh需要免密,使用腳本加配置文件自動批量免密。腳本如下

 

hostip=$1 name=$2 PASSWORD=$3
需要腳本添加上面三個參數或者通過循環一個host文件實現批量即可。
#!/bin/bash
#yum安裝expect
#yum -y install expect
#PWD_1是登陸密碼,可以自己設定
#PASSWORD=123456
#hosts="master slave1 slave2"
#
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 $1@$2;
            expect {
                {Are you sure you want to continue connecting *} {send -- yes\r;exp_continue;}
                {*password:} {send -- $3\r;exp_continue;}
                eof {exit 0;}
            };"
}

check_cmd () {
    if [[ $? == 0 ]];then
        echo "$1 SUCCESS"
    else
        echo "$1 ERROR"
        exit
    fi
}

chmod +x ssh_init.exp 
if [[ ! -e $HOME/.ssh/id_rsa.pub ]]; then
  key_generate && check_cmd "ssh key creat"
fi
hostip=$1
name=$2
PASSWORD=$3
auto_ssh_copy_id $name $hostip  $PASSWORD
./ssh_init.exp $name $hostip  $PASSWORD
check_cmd "ssh scripts run cmd"

 

 

做一個秘鑰檢測,檢測是否成功。

ssh_init.exp 內容如下
#!/usr/bin/expect -f
 
set timeout 2
 
set name [lindex $argv 0]
set node [lindex $argv 1]
set pawd [lindex $argv 2]
 
spawn ssh ${name}@${node}
expect {
    "*yes/no*" {send "yes\n";exp_continue}
    "*password:" {send "$pawd\r"}
}
 
#expect "*${name}@${node}*"
#send "ssh-keygen -t rsa -P ''\r"
#expect "*ssh/id_rsa):"
#send "\r"
#expect {
#    "Overwrite (y/n)?" {send "y\n";exp_continue}
#    "*${name}@${node}*" {send "exit\r"}
#}
expect eof
exit

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM