将短主机名添加到/etc/hosts文件中的Python

2024-04-19 09:09:01 发布

您现在位置:Python中文网/ 问答频道 /正文

当前,我的/etc/hosts文件缺少短主机名(最后一列)是否有方法获取文件remove'中的FQDN值。pdp.wdf.有限公司'并将主机名添加到最后一列。 为了达到这里,我确实写了一个小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()))

cat/etc/主机

^{pr2}$

需要/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

Tags: 文件inreforetcousocketdict
2条回答

您可以使用以下内容进行匹配(使用g全局和m多行标志):

(^[^\s#]+\s+([^.\n]+).*)

并替换为以下内容:

^{pr2}$

RegEX DEMO

好吧,我明白了,但我得调整一下。在

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

更改是在代码中完成的

^{pr2}$

正如预期的那样。在

相关问题 更多 >