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

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

[root@localhost shell-key]# cat arg_list.txt 
172.16.56.237 clouds root  22 172.16.56.215
172.16.56.53  clouds  root 22 172.16.56.215
172.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
"; exp_continue}  
"*password:" { send "$passwd
" }  
}  

expect "*#
"  
send "rm -fr /root/.ssh
"
send "mkdir /root/.ssh
"
send "chmod 700 /root/.ssh
"
send "cd /root/.ssh
"
send "ssh-keygen
"

expect "*_rsa):"
send "
"
expect "*ase):"
send "
"
expect "*again:"
send "
"

expect "#
"  
send  "exit
"  
expect eof  

spawn ssh $username@$remo_ip

expect {
"*yes/no" { send "yes
"; exp_continue}
"*password:" { send "$passwd
" }
}

expect "*#
"
send "scp /root/.ssh/id_rsa.pub $username@$localip:/root/shell-key/pub_key/$key_name
"
expect "*(yes/no)?" 
send "yes
"

expect "*password: 
" 
send "$passwd
"

#expect "*password:
"
#send "$passwd
"


expect "*#
"
send  "exit
"
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 


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

原文地址:https://www.cnblogs.com/osxlinux/p/3521053.html