1.建立一个ip,端口,用户,密码列表
[root@localhost shell-key]# cat arg_list.txt 172.16.56.237 clouds root 22 172.16.56.215172.16.56.53 clouds root 22 172.16.56.215172.16.56.215 clouds root 22 172.16.56.215[root@localhost shell-key]#
2.建立expect交互交脚本:
[root@localhost shell-key]# cat expect_run_config.exp #!/usr/bin/expect -f set ip [lindex $argv 0]set passwd [lindex $argv 1]set username [lindex $argv 2]set port [lindex $argv 3]set localip [lindex $argv 4]set ssh_file [lindex $argv 5]set remo_ip [lindex $argv 6]set key_name [lindex $argv 7]set timeout 5 ##create the key in the every node #生成公共密钥spawn ssh $username@$ip expect { "*yes/no" { send "yes\r"; exp_continue} "*password:" { send "$passwd\r" } } expect "*#\n" send "rm -fr /root/.ssh\r"send "mkdir /root/.ssh\r"send "chmod 700 /root/.ssh\r"send "cd /root/.ssh\r"send "ssh-keygen\r"expect "*_rsa):"send "\r"expect "*ase):"send "\r"expect "*again:"send "\r"expect "#\n" send "exit\r" expect eof spawn ssh $username@$remo_ipexpect {"*yes/no" { send "yes\r"; exp_continue}"*password:" { send "$passwd\r" }}expect "*#\n"send "scp /root/.ssh/id_rsa.pub $username@$localip:/root/shell-key/pub_key/$key_name\r"expect "*(yes/no)?" send "yes\r"expect "*password: \n" send "$passwd\r"#expect "*password:\n"#send "$passwd\r"expect "*#\n"send "exit\r"expect eof [root@localhost shell-key]#
3.建立一个shell循环脚本:
[root@localhost shell-key]# cat loop-out.sh #!/bin/sh#loop_sh.shecho "########******loding*******#########"rm -fr /root/shell-key/pub_key/*rm -fr /root/shell-key/hello.txtwhile read linedo echo $line >> hello.txt done < arg_list.txtsleep 3rm -fr /root/shell-key/exp_list.txtwhile read sldo echo $sl | sed "s/$/ ${RANDOM}.key/" >> exp_list.txtdone < hello.txtsleep 3while read listdo echo $list | awk '{print $1}' rem_ip=$(echo $list | awk '{print $1}') rem_keyname=$(echo $list | awk '{print $6}') ./expect_run_config.exp $list $rem_ip $rem_keynamedone < exp_list.txtcat /root/shell-key/pub_key/* > /root/.ssh/authorized_keysif [ $? -eq 0 ];then echo "******************************************" echo "Congratulations, you create a public key *" echo "******************************************"else echo "Please check_your script $0 and expect config! " echo "Good luck !"fi[root@localhost shell-key]#
4.执行脚本:
[root@localhost shell-key]# ./loop-out.sh