ssh互信自动化脚本(待更新)

时间:2020-12-19 16:40:33

1.建立一个ip,端口,用户,密码列表

[root@localhost shell-key]# cat arg_list.txt
172.16.56.237 clouds root 172.16.56.215
172.16.56.53 clouds root 172.16.56.215
172.16.56.215 clouds root 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 ]
set passwd [lindex $argv ]
set username [lindex $argv ]
set port [lindex $argv ]
set localip [lindex $argv ]
set ssh_file [lindex $argv ] set remo_ip [lindex $argv ]
set key_name [lindex $argv ]
set timeout #
#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_ip expect {
"*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.sh
echo "########******loding*******#########"
rm -fr /root/shell-key/pub_key/*
rm -fr /root/shell-key/hello.txt while read line
do
echo $line >> hello.txt
done < arg_list.txt
sleep 3 rm -fr /root/shell-key/exp_list.txt while read sl
do
echo $sl | sed "s/$/ ${RANDOM}.key/" >> exp_list.txt
done < hello.txt sleep 3 while read list
do
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_keyname
done < exp_list.txt cat /root/shell-key/pub_key/* > /root/.ssh/authorized_keys if [ $? -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 

遍地是高手,我是菜鸟中的菜鸟,不喜勿喷!!!