脚本思路:生成秘钥后,批量传输秘钥,根据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"替换成想要执行的命令。
时间: 2024-10-23 08:04:44