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

Syntax error or access violation: 1118 Row size too large. The maximum row size for the used table type, not counting BLOBs, is 8126.

Problem:

Fatal error: Uncaught exception 'Exception' with message 'exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1118 Row size too large. The maximum row size for the used table type, not counting BLOBs, is 8126. You have to change some columns to TEXT or BLOBs' in /var/www/html/library/Zend/Db/Statement/Pdo.php:228 Stack trace: #0 /var/www/html/library/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array) #1 /var/www/html/library/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array) #2 /var/www/html/library/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array) #3 /var/www/html/library/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('UPDATE `setting...', Array) #4 /var/www/html/library/Zend/Db/Adapter/Abstract.php(632): Zend_Db_Adapter_Pdo_Abstract->query('UPDATE `setting...', Array) #5 /var/www/html/application/controllers/TWController.php(239): Zend_Db_Adapter_Abstract->update('settings', Array, 'id=1') #6 /var in /var/www/html/index.php on line 307

When I tried to copy values from one table to another using phpmyadmin I get #1030 – Got error 139 from storage engine.

After googling for similar problems I found http://forums.mysql.com/read.php?22,63584,63584#msg-63584

Solution: Changing table’s storage engine from “InnoDB” to “MyISAM” helped me.

Permalink is not working in wordpress

If you always get 404 error after changing permalink structure try to check if:

  1. .htaccess file is in the web site root, normally in the same directory where index.php is.
  2. Is .htaccess is readable by web-server.
    The simplest and fastest way to check that is to add an extra line with random text and save it. If you see 500 error then it’s readable. Do not forget to remove extra text.
  3. Is “Rewrite Engine” enabled. Usually it’s enabled by default on majority hosting servers otherwise you should get error 500.
  4. If “Rewrite Engine” works ok but the above did not help you can try this code in your .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !\.(js|ico|gif|jpg|png|css|php|html|src|pdf|zip|txt|doc|docx)$ index.php [L]

“Pending” status in the browser when trying to send data through ajax.

When I tried to send some data to a server using jquery .post() method, I got the “Pending” status in Chrome’s or Firefox network monitoring tool and finally did not get response from the server. I’ve never met such a strange behavior of sending data via ajax, so that was not obvious problem for me.
Later I found out that the data size was about 1Mb, because one hidden field of the form contained a lot of html data.
I used $(“#myform”).serialize() to post all the data from the form.
Then it was necessary to collect values separately, because I needed each field to be tested by size.
Here is a piece of code:

 
$("#gen_pdf").click(
    function(){
        to_pdf = $("#main").html() // size of html data was about 1Mb
        //console.log(to_pdf.length)
        //to_pdf = to_pdf.substr(0, to_pdf.length/3) this still causes "Pending" status
        //reduce size of data just for test
        //to_pdf = to_pdf.substr(0, 40000) this works but with 5 seconds delay. 
        //console.log(to_pdf.length)

        $.post("/layout-builder/generate-pdf/", { 
               id:$("#invoice_id").val(),
               to_pdf_data: to_pdf,
               type:1 
        }, function(response){
               $.get("/layout-builder/preview-with-real-values/id/"+$("#invoice_id").val()+"/", false, previewHtmlCallBack, 'json');
           }, 'json');
        })

Reducing the size of posted data by removing unnecessary html code from #main div solved the problem for me.