Archive - python RSS Feed

capturing environment variables in python

capturing environment variables is very useful when one has to do some hacks..
this is a simple bash script which shows all the environment variables when caught from STDIN

1
2
3
4
5
#!/bin/bash

CAPTURE_FILE=/var/log/capture_data
env >> ${CAPTURE_FILE}
exit 1

Equivalent Python script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python

import os
import sys

def capture():

    log = os.environ
    data = open("/tmp/capture.log", "a")
    for key in log.keys():
        data.write((key))
        data.write(" : ")
        for n in log[key]:
            data.write('%s' % ((n)))
        data.write("\n")
    data.close()
    sys.exit(1)

def main():

    capture()

if __name__ == "__main__":
    main()
 

generating a QRcode in Vcard format in python

You can create a QRcode using the python pygooglechart wrapper for Google chart API. Here i used the wrapper to generate the QRcode as a django app but right now I wont go into the specifics of how to create a django app, maybe will do later,

but this is the view i made for the qr app, i passed the form results to the QRChart and formatted the results in a Vcard format and its then rendered to the page.

You can see the script in action here

http://www.cacoos.com/qr/

test it using an QR android/iphone app

Now the Views….

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.template.loader import get_template
from django.template import Template, Context
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from cacoos_com.qr.qr_form import QrForm
from pygooglechart import QRChart


def qr(request):
    if request.method == 'POST':
        qform = QrForm(request.POST)
        if qform.is_valid():
            qc = qform.cleaned_data
            chart = QRChart(300,300)
            mecard = "BEGIN:VCARD"+"\n"+"VERSION:3.0 \n"+"FN:"+qc['name']+"\n"+"TEL;type=CELL:"+qc['phone']+"\n"+"EMAIL;type=INTERNET;type=WORK;type=pref:"+qc['email']+"\n"+"URL;type=pref:"+qc['url']+"\n"
            chart.add_data(mecard)
            chart.set_ec('H', 0)
            chart.download('/usr/share/pyshared/django/contrib/admin/media/qr-hello.png')
            return render_to_response('qr_results.html', {'url': qc['url'] })
    else:
        qform = QrForm(initial={'url': 'type your url here'})
    return render_to_response('qr_form.html', {'form': qform})

You can use the following template to generate a Vcard, quite handy…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
BEGIN:VCARD
VERSION:3.0
N:Doe;John;;;
FN:John Doe
ORG:Example.com Inc.;
TITLE:Imaginary test person
EMAIL;type=INTERNET;type=WORK;type=pref:johnDoe@example.org
TEL;type=WORK;type=pref:+1 617 555 1212
TEL;type=CELL:+1 781 555 1212
TEL;type=HOME:+1 202 555 1212
TEL;type=WORK:+1 (617) 555-1234
item1.ADR;type=WORK:;;2 Example Avenue;Anytown;NY;01111;USA
item1.X-ABADR:us
item2.ADR;type=HOME;type=pref:;;3 Acacia Avenue;Newtown;MA;02222;USA
item2.X-ABADR:us
NOTE:John Doe has a long and varied history\, being documented on more police files that anyone else. Reports of his death are alas numerous.
item3.URL;type=pref:http\://www.example/com/doe
item3.X-ABLabel:_$!<HomePage>!$_
item4.URL:http\://www.example.com/Joe/foaf.df
item4.X-ABLabel:FOAF
item5.X-ABRELATEDNAMES;type=pref:Jane Doe
item5.X-ABLabel:_$!<Friend>!$_
CATEGORIES:Work,Test group
X-ABUID:5AD380FD-B2DE-4261-BA99-DE1D1DB52FBE\:ABPerson
END:VCARD
 

simplest python class tutorial

A class in python is a blueprint of the instances which you can create from, for example i want to create a house and i have the description and the properties of that house, now I can spawn multiple houses using that blueprint and every instance will be a separate entity from the other but identical in properties defined in the blueprint i.e class

So we create a class house and for example will create three functions i.e one to name the house, location and third to print the properties of that house. Below is a simple class definition, you might be wondering what the hell this “self” is, well basically its a temporary place holder for the object which is created from this class, this helps the class to identify the object and its attributes within the class, in this case its the “first” and “second” object.

1
2
3
4
5
6
7
8
9
10
>>> class house:
...         def houseName(self,name):
...             self.name = name
...         def houseLocation(self,location):
...             self.location = location
...         def printName(self):
...             print "House name: %s " % self.name
...             print "Location: %s " % self.location
...
>>>

The next four steps creates the “first” object from the class “house()” sets the name, location and prints it.

1
2
3
4
5
6
7
>>>
>>> first = house()
>>> first.houseName = "Dog Villa"
>>> first.houseLocation = "Zetland Street"
>>> first.printName()
House name: Dog Villa
Location: Zetland Street

we use the same methods to create the second object “second”

1
2
3
4
5
6
>>> second = house()
>>> second.houseName('Cat street')
>>> second.houseLocation('Sherwood Way')
>>> second.printName()
House name: Cat street
Location: Sherwood Way

Next we will create a parent class and inherit it on a subclass, also see how we can manipulate the inherited variables from the parent class, Note here “pass” in the childClass means “dont do anything”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> class parentClass:
...        var1="i am var1"
...        var2 ="i am var2"
...
>>> class childClass(parentClass):
...        pass
...
>>> parentObject=parentClass()
>>> parentObject.var1
'i am var1'
>>> parentObject.var2
'i am var2'
>>> childObject=childClass()
>>> childObject.var1
'i am var1'
>>> childObject.var2
'i am var2'
>>>

Continue Reading…

 

puppet sync users across all linux machines

Puppet is a very handy package if you have a range of linux machines to configure, here i will try to use puppet to sync users across all machines, there are many who used bash and puppet codings to achieve the same, i prefer to use python. So…..you can feeds the users from a file or from a list in python..

1
users = ["user1","user2","user3","user4","user5]

incase you want to feed from file use the file open function and iterate over the users

1
2
3
4
userfile = open("location of file", "r")
for i in userfile.readlines():
     print i
     (process i i.e. users...)

Continue Reading…

 

python psutil windows process list

Ever wondered how to check what your firefox is doing in the background, using windows processexplorer and a series of these commands on windows will help you trace the process

1
2
3
4
C:'WINDOWS>netstat -an |find /i "listening"
C:'WINDOWS>netstat -an |find /i "established"
C:'WINDOWS>netstat -no
C:'WINDOWS>pulist |find /i "1536"

But a similar but much detailed output can be achieved using the python psutils module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import psutil

def process():
    plist = psutil.get_process_list()
    plist = sorted(plist, key=lambda i: i.name)
    for i in plist:
        if "firefox.exe" in i.name:
            #print i.get_memory_info()
            print "process id ", i.pid
            rss,vms = i.get_memory_info()
            print "memory used ", str(round(i.get_memory_percent(),2))+ "%"
            print "memory used in ram = "+ str(round((float(rss/1024)/1024), 2)) +" MB"
            print "swap memory usage = "+ str(round((float(vms/1024)/1024), 2)) +" MB"
            print "cpu utilization "+ str(i.get_cpu_percent()) +"%"
            user,system = i.get_cpu_times()
            print "cpu time spent outside the kernel ",user
            print "cpu time spent inside the kernel ",system
            #print i.get_connections()
            print "network connections....."
            for g in i.get_connections():
                print "local address "+ str(g[3]) + "-->" + str(g[4]) + " status "+ str(g[5])
            #print i.get_threads()


def main():
    process()


main()

Continue Reading…

 

yum centos repository python script

Keeping a local yum repository is a good idea, you can get a list of all centos mirrors from here

http://www.centos.org/modules/tinycontent/index.php?id=30

The following python script downloads the os and updates for the releases 5.5,5,6 and 6

make sure you create the relevant directories eg:

1
2
mkdir -p /var/www/html/centos/5.5/os/x86_64
mkdir -p /var/www/html/centos/5.5/updates/x86_64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python

import subprocess
import os

def main():
    print "download and sync centos repository.."
    rsync = "/usr/bin/rsync -avrt "
    #mirror = "rsync://mirror.cogentco.com/CentOS"
    mirror = "rsync://anorien.csc.warwick.ac.uk/CentOS"
    ver = ["5.5","5.6","6"]
    arch = ["x86_64"]
    base=["os","updates"]
    local = "/var/www/html/centos"

    for v in ver:
        for a in arch:
            for b in base:
                remote = mirror+"/"+v+"/"+b+"/"+a+"/"
                subprocess.call( rsync+" "+remote+" "+local+"/"+v+"/"+b+"/"+a+"/", shell=True)

    print "completed downloading of updates..."

main()

save the above script and make it executable..

1
chmod 755 /path/to/yum-sync.py

and finally add this script to cron to run every midnight

1
 05 * * * root /path/to/yum-sync.py
 

python calculate mouse speed in miles per hour

this is based on my previous program to find out the cursor location, this time i stored the X,Y coordinates and used the speed = distance/time formula to deduce the mouse speed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
import os
import math
import time
import datetime
from datetime import datetime
from datetime import timedelta
from Xlib import display
import pygame
from pygame.locals import *

PIXEL_MILE_RATIO = 6336000
pixels_to_miles = lambda p: p*PIXEL_MILE_RATIO

def main():
x = 0
y = 0
z = time.time()
start = datetime.now()
end = start + timedelta(minutes = 2)
while start < end:
    a1 = x
    b1 = y
    c1 = z
    #timer = int(end - time.localtime(time.time()).tm_min)
    #dt = datetime.now()
    data = display.Display().screen().root.query_pointer()._data
    x = data["root_x"]
    y = data["root_y"]
    z = time.time()
    m = start.minute
    s = start.second
    nn = start.microsecond
    #x1, y1 = pygame.mouse.get_rel()
    print "x = ", x
    print "y = ", y
    print "t = ", z
    print "M = ", m
    #print "x1 = ", x1
    #print "y1 = ", y1
    a = " X = " + str(x)
    b = " Y = " + str(y)
    c = " CPUTime = " + str(z)
    s1 = " PX = "+ str(a1)
    s2 = " PY = "+ str(b1)
    s3 = " PT = "+ str(c1)
    d = " Time = " + str(m)+":"+str(s)+":"+str(nn)
    dx = float(x) - float(a1)
    dy = float(y) - float(b1)
    dist = math.sqrt( math.pow(dx,2) + math.pow(dy,2))
    dz = (float(z) - float(c1))/3600
    speed = float(pixels_to_miles(dist)/dz)
    print "speed: ", speed
    filename = "mouselog.txt"
    file = open(filename,'a')
    file.write( "speed = "+str(speed) + d + c + a + b + s1 + s2 + s3 + "\n")
    file.close()
    start = datetime.now()

if __name__ == "__main__":
    main()

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
speed = 9.68733413105e+13 Time = 42:15:39331 CPUTime = 1312540935.06 X = 403 Y = 302 PX = 517 PY = 337 PT = 1312540935.03
speed = 3.1195425937e+13 Time = 42:15:56426 CPUTime = 1312540935.08 X = 370 Y = 284 PX = 403 PY = 302 PT = 1312540935.06
speed = 3.35042681035e+12 Time = 42:15:83911 CPUTime = 1312540935.11 X = 369 Y = 280 PX = 370 PY = 284 PT = 1312540935.08
speed = 1.68384671714e+13 Time = 42:15:111970 CPUTime = 1312540935.14 X = 388 Y = 271 PX = 369 PY = 280 PT = 1312540935.11
speed = 2.13257869307e+13 Time = 42:15:140457 CPUTime = 1312540935.15 X = 399 Y = 270 PX = 388 PY = 271 PT = 1312540935.14
speed = 5.35459767736e+13 Time = 42:15:160703 CPUTime = 1312540935.18 X = 464 Y = 271 PX = 399 PY = 270 PT = 1312540935.15
speed = 4.03726000597e+13 Time = 42:15:179963 CPUTime = 1312540935.21 X = 513 Y = 280 PX = 464 PY = 271 PT = 1312540935.18
speed = 4.92414847017e+13 Time = 42:15:208925 CPUTime = 1312540935.25 X = 604 Y = 323 PX = 513 PY = 280 PT = 1312540935.21
speed = 3.59206632608e+12 Time = 42:15:254745 CPUTime = 1312540935.27 X = 605 Y = 325 PX = 604 PY = 323 PT = 1312540935.25
speed = 3.93031983354e+12 Time = 42:15:268934 CPUTime = 1312540935.29 X = 603 Y = 328 PX = 605 PY = 325 PT = 1312540935.27
speed = 1.8299347528e+13 Time = 42:15:289879 CPUTime = 1312540935.31 X = 591 Y = 333 PX = 603 PY = 328 PT = 1312540935.29
speed = 1.91997708739e+13 Time = 42:15:306052 CPUTime = 1312540935.32 X = 582 Y = 335 PX = 591 PY = 333 PT = 1312540935.31
speed = 6.08661375482e+13 Time = 42:15:317059 CPUTime = 1312540935.34 X = 516 Y = 338 PX = 582 PY = 335 PT = 1312540935.32
speed = 4.21959903522e+13 Time = 42:15:341786 CPUTime = 1312540935.36 X = 481 Y = 335 PX = 516 PY = 338 PT = 1312540935.34
speed = 1.58171778767e+14 Time = 42:15:360783 CPUTime = 1312540935.38 X = 343 Y = 309 PX = 481 PY = 335 PT = 1312540935.36
speed = 4.02061707593e+13 Time = 42:15:381011 CPUTime = 1312540935.41 X = 295 Y = 293 PX = 343 PY = 309 PT = 1312540935.38

Technorati Tags:

 

python calculate mouse cursor position

You can use the python-xlib to interact with X11 and get the cursor position, you n the program calculates the cursor position for a duration of 2minutes. I tried using evdev but on my box it was not able to interact with the character device.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python
import os
import time
import datetime
from datetime import datetime
from datetime import timedelta
from Xlib import display

def main():
    start = datetime.now()
    end = start + timedelta(minutes = 2)
    while start < end:
        #timer = int(end - time.localtime(time.time()).tm_min)
        #dt = datetime.now()  
        data = display.Display().screen().root.query_pointer()._data
        x = data["root_x"]
        y = data["root_y"]
        z = time.time()
        m = start.minute
        s = start.second
        nn = start.microsecond
        print "x = ", x
        print "y = ", y
        print "t = ", z
        print "M = ", m
        a = " X = " + str(x)
        b = " Y = " + str(y)
        c = " CPUTime = " + str(z)
        d = " Time = " + str(m)+":"+str(s)+":"+str(nn)
        filename = "mouselog.txt"
        file = open(filename,'a')
        file.write(d + c + a + b + "\n")
        file.close()
        start = datetime.now()
   
if __name__ == "__main__":
    main()

Output is saved in mouselog.txt, this is how it will look in realtime:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Time = 9:53:194640 CPUTime = 1312078193.22 X = 1176 Y = 500
Time = 9:53:225687 CPUTime = 1312078193.25 X = 1209 Y = 457
Time = 9:53:250357 CPUTime = 1312078193.29 X = 1203 Y = 378
Time = 9:53:285457 CPUTime = 1312078193.33 X = 1120 Y = 297
Time = 9:53:334360 CPUTime = 1312078193.37 X = 1067 Y = 293
Time = 9:53:372459 CPUTime = 1312078193.4 X = 1020 Y = 316
Time = 9:53:398025 CPUTime = 1312078193.42 X = 984 Y = 333
Time = 9:53:424195 CPUTime = 1312078193.45 X = 959 Y = 341
Time = 9:53:450570 CPUTime = 1312078193.48 X = 949 Y = 344
Time = 9:53:480339 CPUTime = 1312078193.51 X = 919 Y = 347
Time = 9:53:512055 CPUTime = 1312078193.54 X = 872 Y = 350
Time = 9:53:541836 CPUTime = 1312078193.57 X = 837 Y = 350
Time = 9:53:573826 CPUTime = 1312078193.6 X = 835 Y = 350
Time = 9:53:602601 CPUTime = 1312078193.63 X = 835 Y = 350
 

python apt-get cron updates

I wanted the system to send me a mail every month the updates it has for the packages, i tried using subprocess.Popen, thought to redirect the output to stdin and write it to a file, but it was terrible…something which i  could do easily in bash

apt-get -V upgrade > upgrade.log

after much of research I stumbled across python-apt http://www.wwclass.com/doc/python-apt/html/ and ola it worked like charm!!! below is the script.. Continue Reading…

 

simple log parsing script in python

this is a simple log parsing script, much like many guys split a logfile into chunks using perl/bash, we read the log file line by line, split it , feed it to a list , do the checks and then print it…simple..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    #!/usr/bin/env python
    import sys
    def generate_log_report(logfile):
        for line in logfile:
            line_split = line.split()
            list = [line_split[0], line_split[1], line_split[2], line_split[4]]
            if “named” in list[3]:
                l = [line_split[0], line_split[1], line_split[2], line_split[4]]
                print l
            else:
                li = [line_split[0], line_split[1], line_split[2], line_split[4]]
    #    return l
    if __name__ ==__main__”:
        if not len(sys.argv) > 1:
            print __doc__
            sys.exit(1)
        infile_name = sys.argv[1]
        try:
            infile = open(infile_name, “r”)
        except IOError:
            print “you must specify a valid file
            print __doc__
            sys.exit(1)
        log_report = generate_log_report(infile)
        print log_report
        infile.close()
 
Page 1 of 212»
Theme Tweaker by Unreal