Sunday, February 27, 2011

[Level 3] Python Encapsulation.

There are two ways to implement property encapsulation.

[test1.py]
#!/bin/env python

class C(object):
#class C():
    y = 3
    z = 4

    def __init__(self):
        self.__x = 2
        self.z = 0
        self._z = 00
        self.__z = 000

    def getx(self):
        return self.__x

    def setx(self, val):
        print "x is read only"

    x = property(getx, setx)
#    x = property(getx)
#    x = property(lambda self: self.__x)

c=C()
print(c.x,c.y,c.z)
c.x=3
print(c.x,c.y,c.z)
print c.z
print c._z
print c.__z #AttributeError


[test2.py]
#!/bin/env python
#!/bin/env python
class B(object):
   def __init__(self):
       self.__x = None

   @property
   def x(self):
       """I'm the 'x' property."""
       return self.__x

   @x.setter
   def x(self, value):
       self.__x = value

   @x.deleter
   def x(self):
       del self.__x

b=B()
b.x=12
print(b.x)
print(b.__x) #AttributeError



Wish this helps.
regards,
Stanley Huang

[Level 3] Python Abstract Class Implement

If you want to implement python abstract class,
you could use astract base class of python.
The sample code as the following:

[common.py]
#!/bin/env python
from abc import *
__all__ = ['CommonClass']

class CommonClass:
    __metaclass__ = ABCMeta
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def displayAge(self):
        print 'My age is: %s' % self.age

    @abstractmethod
    def displayName(self):
       pass

[myABC.py]
#!/bin/env python
from common import *
class MyClass(CommonClass):
    def __init__(self, name, age):
        CommonClass.__init__(self, name, age)
   
    def displayName(self):
        print "Hi %s!" % self.name

if __name__ == "__main__":
    st = MyClass('Stanley', 25)
    st.displayAge()
    st.displayName()

execute myABC.py
# ./myABC.py
My age is: 25
Hi Stanley!
#

According to above sample,
if you want to define abstract class,
you have three things to do. (ref. red words in common.py)
1. import abstract base class.
from abc import *
2. define __metaclass__.
__metaclass__ = ABCMeta
3. use decoration of method
@abstractmethod
def method_name(self):
...


And if you want to implement it.
You need to define the abstract method. (ref. red words in myABC.py)
ex. def method_name(self):
...

If you don't define the abstract method, you might got the errormessage.
# cat ./myABC.py
...
#    def displayName(self):
#        print "Hi %s!" % self.name
...
# ./myABC.py
Traceback (most recent call last):
  File "./myABC.py", line 13, in
    st = MyClass('Stanley', 25)
TypeError: Can't instantiate abstract class MyClass with abstract methods displayName

Wish this helps.
regards,
Stanley Huang

Thursday, February 24, 2011

[Level 2] DNS Round Robin.

If you want to setup DNS round robin,
just add the record like below into your database.

; dns round robin
rr      IN      A       192.168.0.101
rr      IN      A       192.168.0.102
rr      IN      A       192.168.0.103


Wish this helps.
regards,
Stanley Huang

Wednesday, February 23, 2011

[Level 2] DNS setup on Ubuntu.

If you want to instal DNS on Ubuntu,
the steps of DNS setup as the following:

1. install bind9
# apt-get -y install bind9

2. setup named.conf.local
# cat /etc/bind/named.conf.local
//
// Do any local configuration here
//

// Consider adding the 1918 zones here, if they are not used in your
// organization
//include "/etc/bind/zones.rfc1918";

# This is the zone definition. replace example.com with your domain name
zone "example.com" {
        type master;
        file "/etc/bind/zones/example.com.db";
        };

# This is the zone definition for reverse DNS. replace 0.168.192 with your network address in reverse notation - e.g my network address is 192.168.0
zone "0.168.192.in-addr.arpa" {
     type master;
     file "/etc/bind/zones/rev.0.168.192.in-addr.arpa";
};

3. setup named.conf.options
# cat /etc/bind/named.conf.options
options {
    directory "/var/cache/bind";

    // If there is a firewall between you and nameservers you want
    // to talk to, you may need to fix the firewall to allow multiple
    // ports to talk.  See http://www.kb.cert.org/vuls/id/800113

    // If your ISP provided one or more IP addresses for stable
    // nameservers, you probably want to use them as forwarders.
    // Uncomment the following block, and insert the addresses replacing
    // the all-0's placeholder.

    forwarders {
        168.95.1.1;
    };

    auth-nxdomain no;    # conform to RFC1035
    listen-on-v6 { any; };
};

4. create zones folder
# mkdir /etc/bind/zones

5. create forward database
# cat /etc/bind/zones/example.com.db
; example.com
$TTL    604800
@       IN      SOA     ns1.example.com. root.example.com. (
                     2006020201 ; Serial
                         604800 ; Refresh
                          86400 ; Retry
                        2419200 ; Expire
                         604800); Negative Cache TTL
;
@       IN      NS      ns1
        IN      MX      10 mail
        IN      A       192.168.0.1
ns1     IN      A       192.168.0.1
www     IN      A       192.168.0.2
mail    IN      A       192.168.0.3
client1 IN      A       192.168.0.201
client2 IN      A       192.168.0.202
client3 IN      A       192.168.0.203
client4 IN      A       192.168.0.204
client5 IN      A       192.168.0.205

6. create reverse database
# cat /etc/bind/zones/rev.0.168.192.in-addr.arpa
; example.com
$TTL    604800
@       IN      SOA     ns1.example.com. root.example.com. (
                     2006020201 ; Serial
                         604800 ; Refresh
                          86400 ; Retry
                        2419200 ; Expire
                         604800); Negative Cache TTL
;

@                 IN      NS      ns1.example.com.
1                 IN      PTR     ns1.example.com.
2                 IN      PTR     www.example.com.
3                 IN      PTR     mail.example.com.
201               IN      PTR     client1.example.com.
202               IN      PTR     client1.example.com.
203               IN      PTR     client2.example.com.
204               IN      PTR     client3.example.com.
205               IN      PTR     client4.example.com.

7. restart DNS server
# /etc/init.d/bind9 restart

8. modify resolv.conf
# cat /etc/resolv.conf
// replace example.com with your domain name, and 192.168.0.1 with the address of your new DNS server.
search example.com
nameserver 192.168.0.1

9. test forward name query:
# dig www.example.com
; <<>> DiG 9.7.0-P1 <<>> www.example.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57524
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 1

;; QUESTION SECTION:
;www.example.com.        IN    A

;; ANSWER SECTION:
www.example.com.    604800    IN    A    192.168.0.2

;; AUTHORITY SECTION:
example.com.        604800    IN    NS    ns1.example.com.

;; ADDITIONAL SECTION:
ns1.example.com.    604800    IN    A    192.168.0.1

;; Query time: 0 msec
;; SERVER: 192.168.1.20#53(192.168.1.20)
;; WHEN: Thu Feb 24 00:25:06 2011
;; MSG SIZE  rcvd: 83

10. test reverse name query:
# nslookup 192.168.0.1
Server:        192.168.0.1
Address:    192.168.0.1#53

1.0.168.192.in-addr.arpa    name = ns1.example.com.


Wish this helps.
regards,
Stanley Huang

[Level 3] How to get option 43 from dchp server.

You can following the steps to implement get option 43 from dhcp server.

[server side]
1. install dhcp  server:
# apt-get install dhcp3-server

2. modify /etc/default/dhcp3-server:
(modify)
INTERFACES="eth0"

3. modify /etc/dhcp3/dhcpd.conf:
(add)
option space VendorInfo;
option VendorInfo.text code 10 = { text };

subnet 192.168.2.0 netmask 255.255.255.0 {
  range 192.168.2.2 192.168.2.9;
  filename "pxelinux.0";
  option subnet-mask 255.255.255.0;
  option broadcast-address 192.168.2.255;
  vendor-option-space VendorInfo;
  option VendorInfo.text "option43 text";
}

4. restart server:
# /etc/init.d/dhcp3-server restart

[client side]
1. modify /etc/dhcp3/dhclient.conf:
(add)
option space VendorInfo;
option VendorInfo.text code 10 = { text };
(modify)
request subnet-mask, broadcast-address, time-offset, routers,
        domain-name, domain-name-servers, domain-search, host-name,
        netbios-name-servers, netbios-scope, interface-mtu,
        rfc3442-classless-static-routes, ntp-servers, VendorInfo.text;

2. restart dhcp client:
# dhclient eth0

3. create python script to get option43.
# cat /getOption43.py
#!/bin/env python
import os, sys
import re

def dec2hex(n):
    return "%X" % n

def hex2dec(s):
    return int(s, 16)

 
def getOption43(
numOption):
    sGrepCmd = '/bin/grep'
    sDhcpclientLeases = '/var/lib/dhcp3/dhclient.leases'
    sFilter = 'vendor-encapsulated-options'
    sOption43 = os.popen('%s %s %s 2>/dev/null | tail -1 | awk "{print(\$3)}"' % (sGrepCmd, sFilter, sDhcpclientLeases)).read()
    aOption43 = re.sub(';$','',sOption43.rstrip()).split(':')
    sVendorInfo = ''
    while True:
        if numOption == hex2dec(aOption43[0]):
            aOption43 = aOption43[2:hex2dec(aOption43[1])+2]
            for nAscii in aOption43:
                sVendorInfo = sVendorInfo + chr(hex2dec(nAscii))
            return sVendorInfo
        else:
            aOption43 = aOption43[hex2dec(aOption43[1])+2:]
            if len(aOption43) == 0: return ''


print getOption43(10)

4. test python
# /getOption43.py
option43 text
#

Wish this helps.
regards,
Stanley Huang

Thursday, February 10, 2011

[Level2] Pass parameters to make.

$ cat Makefile
all:
ifdef aa
        echo "defined"
ifeq "${aa}" "123"
        echo "true"
else
        echo "false"
endif
else
        echo "not defined"
endif
$
$ make
echo "not defined"
not defined
$
$ make aa="000"
echo "defined"
defined
echo "false"
false
$
$ make aa="123"
echo "defined"
defined
echo "true"
true
$


Wish this helps.
 regards,
Stanley Huang

Wednesday, February 9, 2011

[Level2] authorized key for ssh.

If you want to pre-authorized key for ssh loging (without password prompt),
please try the following steps:

1. Create key
stanley@s1$ echo "y" > /tmp/y
stanley@s1$ ssh-keygen -f ~/.ssh/id_rsa -N"" < /tmp/y
2. Verify public key
stanley@s1$ ssh-keygen -f ~/.ssh/id_rsa -y 
3. Copy public key to remote server
stanley@s1$ ssh stanley@s2 echo `cat .ssh/id_rsa.pub` \>\> ~stanley/.ssh/authorized_keys
or
stanley@s1$ ssh-copy-id -i ~stanley/.ssh/id_rsa.pub stanley@s2
4. Test
stanley@s1$ ssh stanley@s2
The authenticity of host 's1 (192.168.1.1)' can't be established.
RSA key fingerprint is xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx.
Are you sure you want to continue connecting (yes/no)? yes
stanley@s2$ exit
stanley@s1$ ssh stanley@s2
stanley@s2$


Wish this helps.
regards,
Stanley Huang