How do you count messages in your gmail ?

Here is the short and dirtyeasy way how to:

First we need to install IMAPClient which extends standard module:

sudo pip install IMAPClient

from imapclient import IMAPClient

server = IMAPClient('imap.googlemail.com', use_uid=True, ssl=True)
server.login('mymailbox@gmail.com', 'password')

for f in server.list_folders():
    if f[2] == '[Gmail]':
        continue
    server.select_folder(f[2])
    all = server.search('ALL', None)
    print('%s : %s' % (f[2], len(all)))

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

Simple site pinger

This simple script pings your websites and notifies when a website is down.
It’s written in python >= 2.5 and might be usefull for administrators and programmers.
Some parts of it was found somewhere in the internet and adjusted a bit for my needs.

Required packages can be installed easily from repository ( Ubuntu example ):

sudo apt-get install python-notify

or using pip/easy_install as well

sudo pip install notify

Running this script from command line is a bit annoying so I put to run it by crontab each 30 min:

$ crontab -e
*/30 * * * * DISPLAY=:0 /usr/bin/python /home/vs/bin/pingwebsites.py

Note that you need to set DISPLAY option to make notification visible for current X session.

#!/usr/bin/env python
from threading import Thread
import subprocess
from Queue import Queue
from pynotify import *

num_threads = 4
queue = Queue()
hosts = [
    ,"mysite.com"
    ,"myanothersite.com"
]
#wraps system ping command
def pinger(i, q):
    """Pings subnet"""
    while True:
        host = q.get()
        #print "Thread %s: Pinging %s" % (i, host)
        ret = subprocess.call("ping -c 5 %s" % host,
                        shell=True,
                        stdout=open('/dev/null', 'w'),
                        stderr=subprocess.STDOUT)
        if ret == 0:
            pass
            #print "%s: is alive" % host
        else:
            init("Server checker")
            msg =  "%s: did not respond" % host
            Notification("Server checker", msg).show()
        q.task_done()
#Spawn thread pool
for i in range(num_threads):

    worker = Thread(target=pinger, args=(i, queue))
    worker.setDaemon(True)
    worker.start()
#Place work in queue
for host in hosts:
    queue.put(host)
#Wait until worker threads are done to exit
queue.join()