Thursday, September 10, 2009

Python inheritance using object and class variables

Standard
Introduction:
When you have been working with Java for many years, it is sometimes fun to delve into other languages to get some new inspiration. For the past few days I have been meddeling around with Python / Django and Google App engine.

A discussion over MSN with a friend resulted in me coding this small example of how Python class and object variables differ greatly from what is normal in Java. Also this example illustrates very simple interitance from object->Vehicle->Car and Truck.

Code:
Package for vehicles:

'''
Created on Sep 10, 2009

@author: nikolaj
'''

class Vehicle(object):
'''
classdocs
'''
number_of_vehicles = 0

def __init__(self, color, number, weight):
self.number = number
self.weight = weight
self.color = color
Vehicle.number_of_vehicles += 1
print '(Initializing Vehicle %s which is of type %s)' % (self.number, type(self))


def __del__(self):
Vehicle.number_of_vehicles -= 1

if Vehicle.number_of_vehicles == 0:
print 'Vehicle: I am the last one on the streets now ...'
else:
print 'Vehicle: There are still %d of us left.' % Vehicle.number_of_vehicles

class Car (Vehicle):
'''
classdocs
'''
number_of_cars = 0

def __init__(self, color, number, passengers, weight):
Vehicle.__init__(self, color, number, weight)
self.passengers = passengers
Car.number_of_cars += 1

def __del__(self):
print 'Car: %s says bye. I am off to the scrap heap' % self.number
Car.number_of_cars -= 1

if Car.number_of_cars == 0:
print 'Car: I am the last Car on the streets now ...'
else:
print 'Car: There are still %d Cars left.' % Car.number_of_cars

def howmany (self):
print "Car: %d cars and %d vehicles in total" % (Car.number_of_cars, Car.number_of_vehicles)

class Truck (Vehicle):
'''
classdocs
'''
number_of_trucks = 0

def __init__(self, color, number, tonnage, weight):
Vehicle.__init__(self, color, number, weight)
self.tonnage = tonnage
Truck.number_of_trucks += 1

def __del__(self):
print 'Truck: %s says bye. I am off to the scrap heap' % self.number
Truck.number_of_trucks -= 1

if Truck.number_of_trucks == 0:
print 'Truck: I am the last Truck on the streets now ...'
else:
print 'Truck: There are still %d Trucks left.' % Truck.number_of_trucks

def howmany (self):
print "Truck: %d trucks and %d vehicles in total" % (Truck.number_of_trucks, Truck.number_of_vehicles)


Executable pyton main

from dk.hsys.model.vehicle import Car
from dk.hsys.model.vehicle import Truck

'''
Created on Sep 10, 2009

@author: nikolaj
'''

def main():

car = Car('Blue', 'RH20358', 4, 725)
car2 = Car('Yellow', 'DC79929', 2, 800)
car2.howmany()

truck = Truck('Red', 'CV34254', 22, 32)
truck2 = Truck('Green', 'BD7638', 2, 4)
truck3 = Truck('Black', 'HG76543', 30, 40)
truck.howmany()

if __name__ == '__main__':
main()



Output:


(Initializing Vehicle RH20358 which is of type )
(Initializing Vehicle DC79929 which is of type )
Car: 2 cars and 2 vehicles in total
(Initializing Vehicle CV34254 which is of type )
(Initializing Vehicle BD7638 which is of type )
(Initializing Vehicle HG76543 which is of type )
Truck: 3 trucks and 5 vehicles in total
Car: RH20358 says bye. I am off to the scrap heap
Car: There are still 1 Cars left.
Car: DC79929 says bye. I am off to the scrap heap
Car: I am the last Car on the streets now ...
Truck: CV34254 says bye. I am off to the scrap heap
Truck: There are still 2 Trucks left.
Truck: BD7638 says bye. I am off to the scrap heap
Truck: There are still 1 Trucks left.
Truck: HG76543 says bye. I am off to the scrap heap
Truck: I am the last Truck on the streets now ...

Tuesday, August 25, 2009

Automount with ssh and nfs

Standard
Introduction

I have for a long time mounted and unmounted network file systems by hand when ever I had a need for them. It is not a big thing, but you have to open a terminal in order to do this every time. I experimented a little with automount and autofs and found, that you can dynamically do things in the mount specification files.

Autofs dynamically executes mount commands triggered when you access a defined folder in your system. This folder then becomes the mount point for a given network or local file system. Another use for autofs is access of cd's, floppies and other removable block devices.

This is especially usefull from a Laptop computer, that sometimes are connected to network file systems behind a firewall, sometimes connected to ssh/sftp systems when you are on the road.

The goal is to be able to dynamically let the laptop figure out, what protocol to use: NFS or SSH/SFTP depending on the location of your connection.

Preparing the software

You will need to add the autofs system to your distribution of choice, this is for Debian / Ubuntu:

$ sudo apt-get install autofs

This will add the autofs system to the list of installed packages on your laptop PC.

You will now need to add netcat and sshfs to your system - it is used to check if a ssh server is accessible and mount the nfs share via SSH if it is:


$ sudo apt-get install netcat sshfs

Autofs will add a daemon to your system for monitoring your configured mount points. The deamon needs to be told to reload configurations whenever you change your configuration:



$ sudo /etc/init.d/autofs reload
Reloading automounter: checking for changes ...
Reloading automounter map for: /misc
Reloading automounter map for: /mnt/media


The configuration for the autofs system is held in files in /etc/auto.* where you can add you mount points as you need them. There is several good examples in the ones already added by default. However I produced a new named auto.media and added it to /etc/auto.master in order to access my media drive. This is the contents:



#!/bin/sh
# check to see if this host has a working internet connection and a IP address
MYIP=`ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`
ping -c 1 ${MYIP} >> /dev/null 2>&1
if [ "$?" -ne "0" ]
then
exit 1;
fi

# check to see if HOSTNAME can be pinged directly - if yes echo the mount lines for nfs
ping -c 1 HOSTNAME >> /dev/null 2>&1
if [ "$?" -eq "0" ]
then
echo "root -fstype=nfs,rw,sync,soft,intr,rsize=8012,wsize=8129 HOSTNAME:/foo/bar/&"
echo "data2 -fstype=nfs,rw,sync,soft,intr,rsize=8012,wsize=8129 HOSTNAME:/foo/bar/&"
echo "download -fstype=nfs,rw,sync,soft,intr,rsize=8012,wsize=8129 HOSTNAME:/foo/bar/&"
exit 0;
fi

# check to see if SSHHOST can be contacted - if yes use the ssh/nfs to mount using fuse
nc -z SSHHOSTNAME 22 > /dev/null 2>&1
if [ "$?" -eq "0" ]
then
echo "-fstype=fuse,rw,nodev,nonempty,noatime,allow_other,max_read=65536 :sshfs\#USER\@SSHHOST:/foo/bar/&"
exit 0;
exit 0;
fi


The file /etc/auto.media listed above should be made executable with permissions 755. When executed it will dynamically produce the contents of the auto.media file depending on the script execution. As a consequence the mount points will not be visible in /mnt until execution of the script has completed. So you will have to cd to a non existing folder like /mnt/media before you actually see it created in /mnt :-)


Conclusion and caveat

The above works fine for me. There could be a problem, if you are on a foreign network, where another server called HOSTNAME exists. You may need to add more intelligent identification check of the HOSTNAME server in order to make this work correctly in all networks.

Tuesday, June 9, 2009

Land Rovers with Perkins diesel?

Standard
In the old days I believe that I read somewhere that Land Rover actually considered using one of the Perkins diesel engines in the Defender models.

It never happened as far as I know.

Never the less: Nothing that can be done to a Defender will be left un done.

Here is a Defender pick up with a Perkins inline 6. The P6.



He must blow those half shafts as quick as he can exchange them ...

Or perhaps even with the great Cummins Turbo diesel also used in the Dodge Rams?

Wednesday, May 13, 2009

LUKS encrypted MiniSD using Ubuntu

Standard
Introduction

I have long been playing with the idea of building an encrypted minisd disk. My lappie has a card reader device, and it seems to be very convenient to use a small MiniSD card to hold keypairs and other sensitive material. But only if properly secured through proper encryption.

I wanted to setup the entire sd card for encryption on a device level. No use of encrypted container files or such.

I feared this to be very difficould, little did I know how easy this really is on the latest Ubuntu release Jaunty Jackelope.

It can be very easily setup using dm-crypt.

Preparing the system

In order to setup device level encryption a few initial steps is needed. What the system does is to inject a level of enctyption between the partion and the file system on top of it.

So firstly you need to add the needed software to the ubuntu system using the software repository:
sudo apt-get install cryptsetup
This will add the needed executables and system libraries to your system. However this will not quite cut it. Remember I mentioned the idea of injecting a layer of security between the partition and the file system?

As a consequence the system needs to load extra functionality on the kernel level to enable this functionality. Add the following three lines to the file /etc/modules:

sudo vi /etc/modules

Add:

aes

dm_mod

dm_crypt


When this is done you will need to reboot your pc or manally load the kernel objects in the above order:

sudo modprobe aes

Repeat this for each module.

Your basic system software should now be ready to fly.

Nuking the device

In order to be sure that no residual stuff is on the sd I decided to nuke it completely as the very first step

Note: THIS WILL FOREVER DESTROY WHAT IS ON THE TARGET DEVICE! You have been warned.

sudo dd if=/dev/urandom of=/dev/mmcblk0

The card reader loads the raw device as /dev/mmcblk(n) the /dev/urandom device is a pseudo device that will generate random data. So I completely fill the card with random data.

To be even more sure stuff is deleted use /dev/random. This will take a bit longer.

Now create a new partition on the device:

sudo parted /dev/mmcblk0 mkpart primary 0 63

This will create a new primary partition from mb 0 to 63. Making a total of 64 megabytes which is the capacity of the small sd.

If the above gives you problems try the graphical GUI though gparted.

This concludes the setup needed to the partition on the sd.

Setup of dm-crypt

We now need to setup the encryption on the device. I chose to create a luks device. This will create a device with "Linux unified key setup". It is a linux standard for encryption, header and data, and should *knock on wood* make it possible to use the same sd on other distros.

Create the encryption:

sudo cryptsetup luksFormat --hash=sha512 --cipher=aes-cbc-essiv:sha256 --key-size=256 /dev/mmcblk0p1

The above will provide a reasonable level of security and can be relaxed and enforced according to your taste. Please see the manual pages.

The process will make you confirm the process by typing in "YES" in capital lettering. After this the system will prompt you for a new passcode.

When this is done take out the sd card, wait a few seconds and reinsert it. The system (gnome) will now prompt you for a passcode. Once the passcode entered above has been keyed in the system will mount a new instance in /dev/mapper/.

For instance my device is called:

/dev/mapper/luks_crypto_e72069ca-04f2-4fd1-824b-aac25c41455b

This then concludes the setup of the encryption. Easy wasn't it?

Setting up a filesystem on your new crypt device
In order to use the new device it must have a file system. You can choose any one you like, but I felt adventurous and created a brand new ext4 device. The latest of the linux file system standard:

sudo mkfs -t ext4 /dev/mapper/luks_crypto_e72069ca-04f2-4fd1-824b-aac25c41455b

Sync the filesystem to the disk:

sync

Eject and re-insert your sd a final time, and you will now see Gnome popping up a file manager listing the contents of your new drive.

Now all you need is to create a folder where your non-root user has read and write access.

The drive mounts in /media/disk