ssh自動互信

1、腳本說明node

一、在任意節點上,以root用戶執行該腳本數組

二、腳本中的數組變量:bash

1)array_user:控制要進行互信的用戶,該腳本中使用的是(root,highgo)ssh

2)array_node:控制要互信的節點的hostnamespa

3)須要在執行腳本的當前目錄下建立log目錄,以存放互信過程當中的日誌.net

4)該腳本中,用戶密碼均爲123456日誌

2、腳本內容get

#!/bin/bashit

array_user=(root highgo)
#array_user=(highgo)
array_node=(gtm gtm_standby node1 node2)io

function expect_root {
/usr/bin/expect << EOF
   spawn /usr/bin/ssh ${1}@${2}
   expect {
     "yes/no" {send "yes\r"; exp_continue}
     "*assword:" {send "123456\r"}
   }
 
   expect {
     "*#" {
       send "/usr/bin/ssh-keygen -t rsa\r";
         expect {
           "*id_rsa):" {send "\n"; exp_continue}
           "(y/n)?" {send "y\r"; exp_continue}
           "passphrase" {send "\n"; exp_continue}
           "again:" {send "\n"}
         }
     }
   }
   expect {
     "*#" {
       send "/usr/bin/scp ${3}/.ssh/id_rsa.pub root@gtm :/opt/ssh/id_${1}_${2}.pub\r";
         expect {
           "yes/no" {send "yes\r"; exp_continue}
           "*assword:" {send "123456\r"}
         }
     }
   }
   expect {
     "*#" {send "exit\n\r"}   
   }
EOF
}

function expect_user {
/usr/bin/expect << EOF
   spawn /usr/bin/ssh ${1}@${2}
   expect {
     "yes/no" {send "yes\r"; exp_continue}
     "*assword:" {send "123456\r"}
   }
   expect {
     "]$ " {
       send "/usr/bin/ssh-keygen -t rsa\r";
         expect {
           "*id_rsa):" {send "\n"; exp_continue}
           "(y/n)?" {send "y\r"; exp_continue}
           "passphrase" {send "\n"; exp_continue}
           "again:" {send "\n"}
         }
     }
   }   
   expect {
     "]$ " {
       send "/usr/bin/scp ${3}/.ssh/id_rsa.pub root@gtm :/opt/ssh/id_${1}_${2}.pub\r";
         expect {
           "yes/no" {send "yes\r"; exp_continue}
           "*assword:" {send "123456\r"}
         }
     }
   }
   expect {
     "]$ " {send "exit\n\r"}
   }
EOF
}

function expect_to {
/usr/bin/expect << EOF
  spawn /usr/bin/scp /opt/ssh/authorized_keys ${1}@${2}:${3}/.ssh/
  expect {
    "yes/no" {send "yes\r"; exp_continue}
    "*assword:" {send "123456\r"}
  }   
  expect "100%"
EOF
}

for user in `echo ${array_user[@]}`
do
  for node in `echo ${array_node[@]}`
  do
    touch /opt/ssh/id_${user}_${node}.pub
    cat /dev/null > /opt/ssh/id_${user}_${node}.pub
        if [ "${user}" = "root" ]; then
          user_home=/root
          expect_root ${user} ${node} ${user_home} > ./log/create_${user}_${node}.log 2>&1
        else
          user_home=/home/${user}
          expect_user ${user} ${node} ${user_home} > ./log/create_${user}_${node}.log 2>&1
        fi;        
    done;
done;

cat /dev/null > /opt/ssh/authorized_keys cat /opt/ssh/id_*.pub > /opt/ssh/authorized_keys for user in `echo ${array_user[@]}` do   for node in `echo ${array_node[@]}`   do         if [ "${user}" = "root" ]; then           user_home=/root         else           user_home=/home/${user}         fi;         expect_to ${user} ${node} ${user_home} > ./log/to_${user}_${node}.log 2>&1   done; done;

相關文章
相關標籤/搜索