link 发表于 2018-8-16 09:16:40

python 之根据自己的需求配置hostname-Ttr

#!/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")


页: [1]
查看完整版本: python 之根据自己的需求配置hostname-Ttr