利用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

利用expect交互完成多台linux主机ssh key推送

上一篇:数据库水平切分的实现原理解析---分库,分表,主从,集群,负载均衡器


下一篇:Linux下Centos7对外开放端口