温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

批量修改主机名脚本

发布时间:2020-07-06 20:07:08 来源:网络 阅读:1486 作者:不再少年狂 栏目:开发技术

脚本思路:生成秘钥后,批量传输秘钥,根据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


注:

  1. 直接执行脚本即可,不需要加参数;

  2. 使用ssh链接的时候,第一次需要输入“yes”来确认,而第二次不需要,这个脚本中ssh-copy-id这一部分,用到了expect的类似于if判断的语句,解决了这个问题;

  3. 秘钥传输成功以后,可以把scp /etc/hosts $dip:/etc替换成想要传输的文件;把ssh $dip "hostname $name"替换成想要执行的命令。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI