目前我的/ etc / hosts文件缺少短主机名(最后一列)是否有办法获取文件中的FQDN值删除'.pdp.wdf.ltd'并将主机名添加到最后一列。 到达这里,我写了一个小的python脚本写到一个文件,但无法继续获得短主机名
#!/usr/bin/env python
import re,subprocess,os,socket
a=subprocess.Popen('ifconfig -a', stdout=subprocess.PIPE, shell=True)
_a, err= a.communicate()
_ou=dict(re.findall(r'^(\S+).*?inet addr:(\S+)', _a, re.S | re.M))
_ou=_ou.values()
_ou.remove('127.0.0.1')
y=[]
for i in _ou:
_z = '{0} ' .format (i), socket.getfqdn(i)
y.append(_z)
_y=dict(y)
_z=(' \n'.join('{0} \t {1}'.format(key, val)for (key,val) in _y.iteritems()))
#IP-Address Full-Qualified-Hostname Short-Hostname
10.68.80.28 dewdfgld00035.pdp.wdf.ltd
10.68.80.45 lddbrdb.pdp.wdf.ltd
10.68.80.46 ldcirdb.pdp.wdf.ltd
10.72.176.28 dewdfgfd00035b.pdp.wdf.ltd
/ etc / hosts文件中需要的输出
##IP-Address Full-Qualified-Hostname Short-Hostname
10.68.80.28 dewdfgld00035.pdp.wdf.ltd dewdfgld00035
10.68.80.45 lddbrdb.pdp.wdf.ltd lddbrdb
10.68.80.46 ldcirdb.pdp.wdf.ltd ldcirbd
10.72.176.28 dewdfgfd00035b.pdp.wdf.ltd dewdfgfd00035b
答案 0 :(得分:1)
答案 1 :(得分:0)
好的,我得到了它,但不得不调整一下。
#!/usr/bin/env python
import re,subprocess,os,socket,shutil
header= """#DO NOT EDIT MANUALLY ## File controlled by SaltStack#
# IP-Address Full-Qualified-Hostname Short-Hostname
#
::1 localhost loopback
127.0.0.1 localhost
"""
a=subprocess.Popen('ifconfig -a', stdout=subprocess.PIPE, shell=True)
_a, err= a.communicate()
_ou=dict(re.findall(r'^(\S+).*?inet addr:(\S+)', _a, re.S | re.M))
_ou=_ou.values()
_ou.remove('127.0.0.1')
y=[]
for i in _ou:
n = socket.getfqdn(i) +'\t'+ (socket.getfqdn(i).split("."))[0]
_z = '{0} ' .format (i), n
y.append(_z)
_y=dict(y)
_z=(' \n'.join('{0} \t {1}'.format(key, val)for (key,val) in _y.iteritems()))
_z = header + _z
def make_version_path(path, version):
if version == 0:
return path
else:
return path + "." + str(version)
def rotate(path,version=0):
old_path = make_version_path(path, version)
if not os.path.exists(old_path):
raise IOError, "'%s' doesn't exist" % path
new_path = make_version_path(path, version + 1)
if os.path.exists(new_path):
rotate(path, version + 1)
shutil.move(old_path, new_path)
_hosts_path = '/etc/hosts'
shutil.copy (_hosts_path, _hosts_path+'_salt_bak')
rotate(_hosts_path+'_salt_bak')
f = open(_hosts_path, "w")
f.write(_z);
f.close()
更改已在代码中完成
y=[]
for i in _ou:
n = socket.getfqdn(i) +'\t'+ (socket.getfqdn(i).split("."))[0]
_z = '{0} ' .format (i), n
y.append(_z)
_y=dict(y)
它按预期工作。