shell 的一个小 脚本模板实现hosts添加
工作中需要指定添加hosts信息到大数据平台集群之中,为方便添加,用shell脚本实现交互添加
测试脚本:
1.addhost.ex (实现分发功能)
#!/usr/bin/expect -f
set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set username [lindex $argv 3]
set userpasswd [lindex $argv 4]
set homepath [lindex $argv 5]
send_user "\n===============================$ip=========================================\n"
set timeout 4
spawn ssh [email protected]$ipset timeout 4
expect {
"(yes/no*" {send "yes\r";exp_continue}
"*assword:" {send "$passwd\r"}
}set timeout 4
expect "$"
send "sudo su - \r"set timeout 4
expect "*assword"
send "$passwd\r"set timeout 4
expect "#"
send "\r"
expect eof
2.addnode.py (生成一段字符串)
import re
port=9101with open('iplist','r') as op:
for i in op.readlines():
regex = re.compile('\s+')
ip=regex.split(i)[0]
hostname=regex.split(i.replace('\n',''))[1]
# print ip,hostname
print "echo -e '"+str(ip)+" \\"+"\\t"+str(hostname)+"' >> /etc/hosts"
3.addhost.sh (命令执行)
#!/bin/bash
python addnode.py > tmphost
sed -i '28r tmphost' addhost.ex
cat addhost.ex
#for ip in `cat ip`;do expect addhost.ex ${ip} 用户 密码;done
sleep 5
###sed -i '29,$[28+`cat tmphost|wc -l`d]' addhost.ex
row=$[28+`cat tmphost|wc -l`]
echo $row
sed -i "29,$row"d addhost.excat addhost.ex
具体脚本通过修改ip 与iplist 执行addhost.sh就搞定添加到指定IP的/etc/hosts中: