Tag Archive - python

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
 

create an snmp nagios plugin using python

To create a nagios plugin we need to keep in the mind the exit codes of the program/plugin which is interpreted by nagios to determine the status of the service.

1
2
3
4
5
Return Code          Status
0                         OK. The service is functioning normally
1                         WARNING. The service is about to reach to a critical state prior flagging it as CRITICAL
2                         CRITICAL. The service is down
3                         UNKNOWN. the plugin cannot determine the status of the service.

So any plugins you make should have an exit status, depending on the checks performed, here we will create a python snmp plugin using the pysnp module, the script also uses the optparse module so that arguments can be passed to the command line. Based on my previous post to monitor mysql database using mysql-snmp NetSNMP agent, I used the python pysnmp module to poll the mysql mib on the remote mysql server.

First create the host,hostgroup and the service for checking mysql innodb transactions in nagios

1
2
3
4
5
6
7
8
define host{
        use                     linux-server            ; Name of host template to use
       ; This host definition will inherit all variables that are defined
       ; in (or inherited by) the linux-server host template definition.
        host_name               mysqlserver
        alias                      mysqlserver
        address                 192.168.221.188
        }

Continue Reading…

 

python md5 or sha1 hash of files

Creating a copy of MD5 hash of all critical files on your system is a good idea as such you can track any changes in the files. Linux has a built in tool “md5sum” which does the job, so to create a md5 hash use the md5sum command

1
2
[root@server ~]# md5sum install.log
e04dda261d4f5fed7f2f40d4cd6b7705  install.log

the output can be stored as a database

1
[root@server ~]# md5sum install.log > database

and recheck the database using

1
2
[root@server ~]# md5sum -c database
install.log: OK

this is plain and cool, now we explore python’s way of creating an elegant md5 or sha1 hash utility, and this can be done using the built-in hashlib module. You need to have python > 2.4

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 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