Method 1 Using Expect
1. install Expect using yum
yum install expect -y
2. create an exp script to call ssh-keygen and generate the key files
vim ssh-keygen.exp
!/usr/bin/expect
set enter "\n"
spawn ssh-keygen -t dsa
expect {
"*(/home/root/.ssh/id_dsa)" {send "\n\r";exp_continue}
"*(empty for no passphrase)" {send "\n\r";exp_continue}
"*again" {send "\n\r"}
}
expect eof
3.create the auto distribute script
vim fenfa_sshkey.sh
!/bin/sh
expect ssh-keygen.exp &>/dev/null
. /etc/init.d/functions
for ip in 100 101 102
do
expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub 192.168.112.$ip >/dev/null 2>&1
expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub 192.168.112.$ip &>/dev/null
if [ $? -eq 0 ];then
action "192.168.112.$ip" /bin/true
else
action "192.168.112.$ip" /bin/false
fi
done
4. create expect script
vim fenfa_sshkey.exp
!/usr/bin/expect
if { $argc != 2 } {
send_user "usage: expect fenfa_sshkey.exp file host\n"
exit
}
define var
set file [lindex $argv 0]
set host [lindex $argv 1]
set password "123456"
spawn scp /etc/hosts [email protected]:/etc/hosts
spawn scp -P52113 $file oldboy@$host:$dir
spawn ssh-copy-id -i $file "-p 52113 oldboy@$host"
spawn ssh-copy-id -i $file "-p 22 lx888@$host"
expect {
"yes/no" {send "yes\r";exp_continue}
"*password" {send "$password\r"}
}
expect eof