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

python ftp and get recent file

the following is a script which downloads the latest image from  one of the NASA ftp server at eol.jsc.nasa.gov and to my amazement there are new images every 5 mins!, so I sent python to grab that image….

python supports ftp by importing the ftplib module and ftplib.FTP class.

connecting to an ftp server is very straightforward…

1
2
3
4
5
>>>from ftplib import FTP
>>>f = FTP('my ftp server ')
>>>f.login('anonymous', 'your@email.address')
:
>>>f.quit()

The core job inside in this script is to first dump the listing of files into a list, then reading that list line by line, split the date and convert it to a datetime object and store it in a new list, also i created another list which stores the filenames, next i combined these two lists to form a dictionary, and sorted the dictionary using the KEY(datetime object) in reverse order, and ran the loop only once as i need only the first image.

here is the full 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
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
62
63
64
#!/usr/bin/env python

import ftplib
import os
import socket
import sys
import time
import datetime

HOST = 'eol.jsc.nasa.gov'


def main():
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror), e:
        print 'cannot reach to %s' % HOST
        return
    print "Connect to ftp server"

    try:
        f.login('anonymous','alpha@krisindigitalage.com')
    except ftplib.error_perm:
        print 'cannot login anonymously'
        f.quit()
        return
    print "logged on to the ftp server"


    data = []
    f.dir(data.append)
    datelist = []
    filelist = []
    for line in data:
        col = line.split()
        datestr = ' '.join(line.split()[0:2])
        date = time.strptime(datestr, '%m-%d-%y %H:%M%p')
        datelist.append(date)
        filelist.append(col[3])

    combined = zip(datelist,filelist)
    new_dict = dict(combined)
#    print who
#    for key,value in sorted(new_dict.iteritems(), key =lambda (k,v): (v,k)):

    for key in sorted(who.iterkeys(), reverse=True):
       print "%s: %s" % (key,new_dict[key])
       filename = new_dict[key]
       print "file to download is %s" % filename
       try:
           f.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
       except ftplib.err_perm:
           print "Error: cannot read file %s" % filename
           os.unlink(filename)
       else:
           print "***Downloaded*** %s " % filename
       return

    f.quit()
    return


if __name__ == '__main__':
    main()
 

Active vs Passive Ftp

a simple diagram which shows the difference between active and passive ftp

ACTIVE FTP

 

PASSIVE FTP

 

 

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…

 

Kyokushin Punches \ Tuski

python amazon ec2 retrieve instance values

Using python boto module its fairly easy to list all the attributes
you need to install the python boto package first, if you are using debian run this

1
2
3
4
5
root@localhost#apt-get install python-boto

or for centos

root@localhost#yum install python-boto

we start out script with first importing the boto module

1
2
from boto import ec2
import boto.ec2

Continue Reading…

 

veritas VxVM create a mirrored volume from two concatenated plexes

veritas

 

This is a typical example on how to to create a veritas volume with concatenated plexes. The disk has two disk controllers c1&c2 with two disks eack. We will create veritas disk out of them and assign them a unique name eg. disk1,disk2,disk3 and disk4.

Before we install veritas storage foundation we should know what the different raid levels are:

raid 0 (Disk Spanning): there are two modes here:

1. Concatenation:- which means data is written to both the drives i.e. if we have two drives A and B, system will first write data to disk A and when it is full it will start writing data to B.

2. Stripping:- this means that the systems writes data in such a way that it spreads on both the disks A and B

raid 1: (Redundancy)

1. Mirroring: In this method the system copies the data to the secondary disk in the raid configuration which makes a exact replica of the first disk.

2. Resilence: This method combines two layout to build a volume:

a.) RAID 0+1: it combines Level 0 (Stripping) and Level 1 (Mirroring)
b.) RAID 1+0: it combines Level 1 (Mirroring) and Level 0 (Stripping)

Continue Reading…

 

Quick Install and Configure Puppet with Modules

Puppet install is pretty straightforward

this article is based on these versions

puppet-2.6.6-3.fc15.noarch
puppet-server-2.6.6-3.fc15.noarch

on the master server install puppet-server

1
yum install puppet-server

and on the clients
Continue Reading…

 

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…

 
Page 1 of 1112345678910»...Last »
Theme Tweaker by Unreal