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 = ‘’
If it responds then script updates /etc/hosts like:
If Im at home then it becomes like: (remote ip of a computer in the office )


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

File: ~/

#!/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
        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)
        msg =  "Im in the office, set host ip to %s" % local_ip
        #Im at home
        a.set("/files/etc/hosts/%s/ipaddr" % index, remote_ip)
        a.set("/files/etc/hosts/%s/canonical" % index, host)
        msg =  "Im at home, set host %s ip to %s " % ( host, remote_ip )

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

host = ''
local_ip = ''
remote_ip =''

ret ="ping -c 5 %s" % local_ip,
                stdout=open('/dev/null', 'w'),
if ret == 0:
    setHostAt('work', local_ip, remote_ip)
    setHostAt('home', local_ip, remote_ip)

You can now check it with : sudo ~/