Skip to content

Instantly share code, notes, and snippets.

@wention
Created December 30, 2019 07:57
Show Gist options
  • Select an option

  • Save wention/03eb4fa44b266373502b01e2da4f6c69 to your computer and use it in GitHub Desktop.

Select an option

Save wention/03eb4fa44b266373502b01e2da4f6c69 to your computer and use it in GitHub Desktop.
update /etc/hosts with new hostname
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import logging
# imported from parent directory
import utils
LOG = logging.getLogger(__name__)
LOG.info("Init module %s", __name__)
def main():
hostname = "localhost-{}".format(utils.random_string(6))
out, err, ret = utils.cmd_run(['hostnamectl', 'set-hostname', hostname])
if ret != 0:
LOG.error("Failed to reset hostname(%d)", ret)
LOG.error("DUMP: %s", out)
return
# Update /etc/hosts
r1 = "127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 {}".format(hostname)
r2 = "::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 {}".format(hostname)
r3 = "127.0.1.1 {}".format(hostname)
replace_ts = [
(r"^127\.0\.0\.1.*$", r1),
(r"^::1.*$", r2),
(r"^127\.0\.1\.1.*$", r3),
]
hosts = utils.read_file("/etc/hosts")
for pattern, replace in replace_ts:
hosts = re.sub(pattern, replace, hosts, flags=re.MULTILINE)
LOG.info(hosts)
def run():
main()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment