1. 程式人生 > 實用技巧 >利用expect互動完成多臺linux主機ssh key推送

利用expect互動完成多臺linux主機ssh key推送

expect主要是用於自動化互動動作的。

安裝expect:yum -y install expect

步驟:

1.生成金鑰對

[root@localhost ~]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:p3XYrXIR/nNygTh7ahcmCX9W1SCXlGKb3eQV5timWw8 root@localhost
The key's randomart image is:
+---[RSA 2048]----+
|            ..+*o|
|            ooB =|
|           ..* Bo|
|         . ++o=.o|
|        S *o*oEo |
|         + =oOo.o|
|        . ..Bo= +|
|           +o. = |
|          ...    |
+----[SHA256]-----+

2.建立expect指令碼

[root@localhost ~]# cat fenfa_sshkey.exp
#!/usr/bin/expect
#Use expect finish ssh_key send file
if { $argc != 2 } {
send_user "Usage: expect fenfa_sshkey.exp file host\n"             #判斷條件,如果不滿足2個引數就提示
exit
}

#define  var
set file [lindex $argv 0]                         #set定義變數file
set host [lindex $argv 1]                         #set定義變數host
set password "123456"                             #set定義變數password

spawn ssh-copy-id -i $file "-p22 root@$host"      #spawn定義要執行的命令
expect {                                          #定義expect開始
        "yes/no"        {send "yes\r";exp_continue}        #提示“yes/no”,就傳送yes並回車繼續
        "*password"     {send "$password\r"}               #提示”***password“,就傳送定義password變數並回車
}
expect eof

3.如果是多臺或者成千上百臺怎麼辦?

#!/bin/sh
. /etc/init.d/functions
for ip in `cat ip_list`
do
        expect fenfa_sshkey.exp ~/.ssh/id_rsa.pub $ip
        if [ $0 -eq 0 ];then
                action "$ip" /bin/true
        else
                action "$ip" /bin/false
        fi
done