python主机配置_python 之根据自己的需求配置hostname

#!/usr/bin/env python

# _*_coding:utf-8 _*_

'''

如需批量配置运行方式:通过ansible运行此脚本即可

ansible testserver -m script -a "chage_hostname.py"

'''

import os

shell = "/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d 'addr:'" #定义获取IP地址的shell命令

res = os.popen(shell,'r',0) #执行shell命令,并返回值

ipaddr = str(res.read()) #读取返回值,也就是IP地址

str_ip = ipaddr.replace('.','-') #将IP地址中的“.”替换成“-”

hostnames = 'ambari-%s' % str_ip #组成完整的计算机名

os.environ['new_name']=str(hostnames) #将python变量可传递给shell

os.system('hostname $new_name') #修改计算机名

str_hosts = "%s %s" % (ipaddr,hostnames) #组成"ip hostname"形式,写入/etc/hosts文件

os.environ['ip_host']=str(str_hosts) #将python变量可传递给shell

os.system('rm -rf /etc/hosts')

os.system('echo $ip_host >> /etc/hosts')

os.system("echo '127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4' >> /etc/hosts")

os.system("echo '::1         localhost localhost.localdomain localhost6 localhost6.localdomain6' >> /etc/hosts")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值