腳本思路:生成祕鑰後,批量傳輸祕鑰,根據hosts文件批量修改主機名。
運行環境:用戶名統一是root,密碼統一是123456
腳本
#!/bin/bash # check expect first ############################################################# passwd=123456 key=/root/.ssh/id_rsa ip=`ifconfig eth0 | sed -n '2p'| cut -d: -f2 | cut -d" " -f1` lname=`cat /etc/hosts | grep ^$ip | awk '{print $2}'` # change local hostname sed -i "s/^HOS.*/HOSTNAME=$lname/" /etc/sysconfig/network; hostname $lname # ssh-keygen if [ ! -f $key ];then /usr/bin/expect <<END spawn ssh-keygen -b 1024 -t rsa expect "*id_rsa*" send "\r" expect "*passphrase):" send "\r" expect "*again:" send "\r" expect eof END fi # ssh-copy-id for dip in `cat /etc/hosts |grep -v $ip | awk 'NR>2 {print $1}'|grep -v ^#` do expect -c " set timeout -1 spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $dip expect { \"*yes/no*\" {exp_send \"yes\r\"; exp_continue} \"*password:\" {send \"$passwd\r\"} } expect eof" scp /etc/hosts $dip:/etc name=`grep ^$dip /etc/hosts | awk '{print $2}'` ssh $dip "sed -i "s/^HOS.*/HOSTNAME=$name/" /etc/sysconfig/network" ssh $dip "hostname $name" done
注:
直接執行腳本即可,不需要加參數;
使用ssh鏈接的時候,第一次需要輸入“yes”來確認,而第二次不需要,這個腳本中ssh-copy-id這一部分,用到了expect的類似於if判斷的語句,解決了這個問題;
祕鑰傳輸成功以後,可以把scp /etc/hosts $dip:/etc替換成想要傳輸的文件;把ssh $dip "hostname $name"替換成想要執行的命令。