|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#!/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"
)
|
本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/1875874