vim ip_pass.txt

192.168.40.131 1234
192.168.40.132 1234
192.168.40.133 1234


cat ssh5.exp 
#!/usr/bin/expect
set ipaddr  [lindex $argv 0]
set name "root"
set passwd  [lindex $argv 1]
set timeout 30
spawn ssh-keygen   
expect {
"continue connecting (yes/no)" { send "yes\r";exp_continue }
"Enter file in which to save the key" { send "\r";exp_continue }
"Overwrite (y/n)" { send "n\r";exp_continue }
"Enter passphrase" { send "\r";exp_continue }
"Enter same passphrase" { send "\r";exp_continue }
}


#expect "#" 
set timeout 30
#send "ls /root/.ssh/\r"
set timeout 30
spawn ssh-copy-id $ipaddr
expect {
"continue connecting (yes/no)" { send "yes\r";exp_continue }
"password" { send "$passwd\r" }
}
set timeout 30

expect "#"

spawn  ssh $ipaddr
send "hostname \r"

send "exit\r"
expect eof



#!/bin/bash
echo
for ip in `awk '{print $1}' /root/ip_pass.txt`
do
    pass=`grep $ip /root/ip_pass.txt|awk '{print $2}'`
    expect /root/ssh5.exp $ip $pass
done

 

 
[root@host2 ~]# ssh 192.168.40.133
Last login: Sun May 19 09:48:10 2024 from 192.168.40.131
[root@host4 ~]# exit
登出
Connection to 192.168.40.133 closed.
[root@host2 ~]# ssh 192.168.40.132
Last login: Sun May 19 09:48:06 2024 from 192.168.40.131
[root@host3 ~]# exit
登出
Connection to 192.168.40.132 closed.
[root@host2 ~]# ssh 192.168.40.133
Last login: Sun May 19 09:49:04 2024 from 192.168.40.131
[root@host4 ~]# exit
登出