简体   繁体   English

使用python将短主机名添加到/ etc / hosts文件中

[英]Adding short-hostname into the /etc/hosts file with python

Currently my /etc/hosts file is missing the short-hostname(last column) is there a way to take the FQDN value in the file remove '.pdp.wdf.ltd' and add the hostname to the last column. 当前我的/ etc / hosts文件缺少短主机名(最后一列),是否有办法将文件中的FQDN值删除“ .pdp.wdf.ltd”并将主机名添加到最后一列。 To reach till here I did write a small python script wrote it to a file, but unable to proceed to get the short-hostname added 到这里为止,我确实写了一个小的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/hosts 猫/ etc / hosts

#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  

Output needed in the /etc/hosts file / 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

You can use the following to match (with g lobal and m ultiline flags) : 您可以使用以下内容进行匹配(带有g lobal和m ultiline标志):

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

And replace with the following: 并替换为以下内容:

\1\2

See RegEX DEMO 参见RegEX DEMO

Okies I got it but had to tweak around a bit. 好的,我明白了,但是不得不稍作调整。

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

The change was done in the code 更改已在代码中完成

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)

And it worked as expected. 它按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM