How to update /etc/hosts with python script

Here is the quick dirty script which helps me to update a /etc/hosts automatically.
It’s simply pings a computer in the office network, in my case its: local_ip = ‘192.168.1.120’
If it responds then script updates /etc/hosts like: mysupersite.com 192.168.1.120.
If Im at home then it becomes like: mysupersite.com 289.38.34.116 (remote ip of a computer in the office )

Requirements:

sudo apt-get install augeas-tools python-augeas python-notify2

File: ~/hosts.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import os
import subprocess
import sys
from pynotify import *

__mydir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, __mydir + "/..")

import augeas

def setHostAt(at, local_ip, remote_ip):
    """docstring for setHostAt"""
    MYROOT = '/'
    a = augeas.Augeas(root=MYROOT)
    #matches = a.match("/files/etc/hosts/*[. = '%s']" % host)
    matches = a.match("/files/etc/hosts/*/*[ . = '%s']" % host)
    if matches:
        index = matches[0].split('/')[4]
        record_exists = True
        print(index)
    else:
        record_exists = False
        index = len(a.match("/files/etc/hosts/*"))
        print ( index)

    if at == 'work':
        #Im at work
        a.set("/files/etc/hosts/%s/ipaddr" % index, local_ip)
        a.set("/files/etc/hosts/%s/canonical" % index, host)
        a.save()
        msg =  "Im in the office, set host ip to %s" % local_ip
    else:
        #Im at home
        a.set("/files/etc/hosts/%s/ipaddr" % index, remote_ip)
        a.set("/files/etc/hosts/%s/canonical" % index, host)
        a.save()
        msg =  "Im at home, set host %s ip to %s " % ( host, remote_ip )


    init("Server checker")
    Notification("Server checker", msg).show()

host = 'mysupersite.com'
local_ip = '192.168.1.120'
remote_ip ='289.38.34.116'

ret = subprocess.call("ping -c 5 %s" % local_ip,
                shell=True,
                stdout=open('/dev/null', 'w'),
                stderr=subprocess.STDOUT)
if ret == 0:
    setHostAt('work', local_ip, remote_ip)
else:
    setHostAt('home', local_ip, remote_ip)

You can now check it with : sudo ~/hosts.py

Leave a Reply

Your email address will not be published. Required fields are marked *


*