批量修改主机名脚本
脚本思路:生成秘钥后,批量传输秘钥,根据hosts文件批量修改主机名。
运行环境:用户名统一是root,密码统一是123456
脚本
#!/bin/bash#checkexpectfirst#############################################################passwd=123456key=/root/.ssh/id_rsaip=`ifconfigeth0|sed-n'2p'|cut-d:-f2|cut-d""-f1`lname=`cat/etc/hosts|grep^$ip|awk'{print$2}'`#changelocalhostnamesed-i"s/^HOS.*/HOSTNAME=$lname/"/etc/sysconfig/network;hostname$lname#ssh-keygenif[!-f$key];then/usr/bin/expect<<ENDspawnssh-keygen-b1024-trsaexpect"*id_rsa*"send"\r"expect"*passphrase):"send"\r"expect"*again:"send"\r"expecteofENDfi#ssh-copy-idfordipin`cat/etc/hosts|grep-v$ip|awk'NR>2{print$1}'|grep-v^#`doexpect-c"settimeout-1spawnssh-copy-id-i/root/.ssh/id_rsa.pub$dipexpect{\"*yes/no*\"{exp_send\"yes\r\";exp_continue}\"*password:\"{send\"$passwd\r\"}}expecteof"scp/etc/hosts$dip:/etcname=`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"替换成想要执行的命令。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。