1 实现expect自动生成ssh-keygen 然后复制pub key到其他主机

 yum -y install expect

(传入3个参数 缺点只能传public key到一台主机)

[root@server1 scripts]# cat auto_ssh.sh
#!/usr/bin/expect 
set timeout 10 
set username [lindex $argv 0] 
set password [lindex $argv 1] 
set hostname [lindex $argv 2] 
spawn ssh-keygen -t rsa
expect {
        "*file in which to save the key*" {
            send "\n\r"
            send_user "/root/.ssh\r"
            exp_continue
        "*Overwrite (y/n)*"{
            send "n\n\r"
        }
        }
        "*Enter passphrase*" {
            send "\n\r"
            exp_continue
        }
        "*Enter same passphrase again*" {
            send "\n\r"
            exp_continue
        }
}
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $username@$hostname
expect {
            #first connect, no public key in ~/.ssh/known_hosts
            "Are you sure you want to continue connecting (yes/no)?" {
            send "yes\r"
            expect "password:"
                send "$password\r"
            }
            #already has public key in ~/.ssh/known_hosts
            "password:" {
                send "$password\r"
            }
            "Now try logging into the machine" {
                #it has authorized, do nothing!
            }
        }
expect eof

2 实现上述脚本, 传入一批主机,并把public key传到一批主机上

实现过程:创建循环脚本和主机列表清单txt 使用循环语句重复执行expect脚本

(利用上述expect脚本 不用传入参数即可循环执行)

用法:把3个文件放在/scritps/之下

主机名/IP写入 serverip.txt

修改auto_issue_SSHpubkey.sh里的密码

[root@server1 scripts]# cat auto_issue_SSHpubkey.sh
#!/bin/bash
user="root"
passwd="rootpasswd"
for i in `cat /scripts/serverip.txt`;do
/scripts/auto_ssh.sh $user $passwd $i
done
[root@server1 scripts]# cat serverip.txt
192.168.8.1*
192.168.8.2*

3 运行出现错误 spawn: command not found

作为sh 命令行参数来运行。那么脚本的#! 的一行就会失效

所以才会出现spawn not found 错误,所有上面的auto_ssh.sh脚本必须用以前命令运行

./auto_ssh.sh