Posts

Showing posts from March, 2011

[Level 2] gtk shell script for gcc/vala

1. get vala syntax from gnome [gcc.sh] #!/bin/bash -vx output=`echo $1 | sed -e 's/\.c$//'` gcc -Wall $1 -o $output `pkg-config --cflags --libs gtk+-2.0` $output $ alias gcc='./gcc.sh ' $ gcc ./1.helloworld.c [valac.sh] #!/bin/bash output=`echo $1 | sed -e 's/\.vala$//'` /usr/bin/valac --pkg gtk+-2.0 $1 $output $ alias valac='./valac.sh ' $ valac ./3.helloworld.vala Wish this helps. regards, Stanley Huang

[Level 2] How to verify instance has attribute (variables in global/local) or not.

$ cat ./test1.py #!/bin/env python class myClass: def __init__(self): self.attr1 = 'a' self.attr2 = 'b' def checkAttr(self, sAttr): return hasattr(self, sAttr) mc = myClass() print hasattr(mc, 'attr1') print hasattr(mc, 'attr2') print hasattr(mc, 'attr3') print mc.checkAttr('attr1') print mc.checkAttr('attr2') print mc.checkAttr('attr3') $ ./test1.py True True False True True False $ cat ./test2.py #!/bin/env python ## cannot extract test locals() in another method! ## def testExistInGlobal(): # print globals() # print locals() print 'a in globals(): %s' % ('Ture' if 'a' in globals() else 'False') print 'b in globals(): %s' % ('Ture' if 'b' in globals() else 'False') # print 'a in locals(): %s' % ('Ture' if 'a' in locals() else 'False') # print 'b in locals(): %s' %

[Level 2] get broadcast by Python

I wrote a python script to get broadcast by giving ip and netmask. And I use "lambda" and "map" function to shorten my code, so it's also a good sample for you to study map function. More information please refer here . The sample code is as the following: #!/bin/env python def getBroadcast(self, ip=None, netmask=None): if not ip or not netmask: return None ip = ip.split('.') netmask = netmask.split('.') for n in range(0,4): if netmask[n] == '0': break bc = (map(lambda a, b: str(int(a, 10)&int(b,10)), ip[0:n]+['255']*(4-n), netmask[0:n]+['255']*(4-n))) if n > 1: bc[n-1] = str(int(bc[n-1]) + (255 - int(netmask[n-1]))) return '.'.join(bc) print getBroadcast('192.168.10.1','255.255.254.0') Result: 192.168.11.255 Wish this helps. regards, Stanley Huang

[Level 2] Get ether list by Python in Ubuntu.

#!/bin/env python def getEtherList(): return [x.strip() for x in \ os.popen("ifconfig -a | \ grep Link | grep '^[^ ]' | \ grep -v lo | awk '{print($1)}'")\ .readlines()] print getEtherList() Wish this helps. regards, Stanley Huang

[Level 2] iif in Python

If you want to implement iif in Python, please refer to the following sample code: #!/bin/env python def iif(b): return 'It\'s True' if b else 'It\'s False' print iif(True) print iif(False) And the following sample, guess what will you get! #!/bin/env python b = True print 'b: %s' % 'Ture' if b else 'False' b = False print 'b: %s' % 'Ture' if b else 'False' Result: $ ./iif.py b: Ture False The second result is "False", not "b: False". Why??? Because the prededence of string concatenation is higher than if. Therefore you need to use () to make it correct. #!/bin/env python b = True print 'b: %s' % 'Ture' if b else 'False' b = False print 'b: %s' % ('Ture' if b else 'False') Wish this helps. regards, Stanley Huang

[Level 2] Implement prefix and netmask transfer with Python.

Sometimes, you want to transfer between netmask and prefix setting. You can use the following sample script which is written by Python. #!/bin/env python def transferPrefix2Netmask(self, prefix): netmask = '' nLeadingFF = prefix / 8 netmask += '.'.join(['255']*nLeadingFF) if nLeadingFF != 4: netmask += '.' + str(256-2**(8-prefix%8)) nSuffix00 = 3 - nLeadingFF if nLeadingFF < 3: netmask += '.' + '.'.join(['00']*nSuffix00) return netmask def transferNetmask2Prefix(self, netmask): prefix = 0 left = 0 for i in netmask.split('.'): if i == '255': prefix += 8 else: left = int(i) break if left != 0: for n in range(7, 0, -1): prefix += 1 if left - 2 ** n == 0: break

[Level 2] How to reset interface seq. no in Ubuntu

If you want to reset the seq. no of interface. You can remove the record in /etc/udev/rules.d/70-persistent-net.rules. Wish this helps. regards, Stanley Huang

[Level 2] How to change passphrase by openssl in.

If your company give you the key and cert for openvpn, but somehow you want to change the passphrase that you easy to remember. You can use openssl to modify the passphrase. The sample as below: Step 1, Remove the password: # openssl rsa -in client.key -out client2.key (It will prompt you for the current password, and write the decrypted key to client2.key) Step 2, Add or change the password: # openssl rsa -in client.key -out client2.key -des3 (It will prompt you for the current password (if any), then for the new password, and then write the encrypted key to client2.key) Wish this helps. regards, Stanley Huang

[Level 3] How to implement "Press any key to continue" in Python.

When you develop a terminal program, you always need a function to "Press any key to continue", but how to implement it in Python script. I found out a sample on here: http://code.activestate.com/recipes/134892/ Wish this helps. regards, Stanley Huang

[Level 3] How to implement reflection in Python.

The Python Code: #!/bin/env python def f1(): exec 'a=1' def f2(): exec 'global a; a=2' def f3(): print a global a a=0 f1() f3() f2() f3() The output is: # /tmp/t.py 0 2 As you can see, The f1() function cannot modify global variable "a" successfully, we can say that, exec is a fact function, and unless you declare a variable as a global variable, or you just deal with a local variable. Like f1() So if you want to deal with global variable, please remember to declare it as the global variable first. Like f2() Wish this helps. regards, Stanley Huang

[Level 2] How to reserve ip (query only) from dchp server by dhclient in Ubuntu.

If you want to reserve ip (query only) from dhcp server by dhclient in Ubuntu, you can use the following command to do so. # dhclient -q -sf /dev/null -lf /tmp/dhclient.lease -pf /tmp/dhclient.pid Then you can see the lease file (/tmp/dhclient.lease) to get more information. PS. In my test, dhclient 3.1 ( in Ubuntu 10.04 ) will have an error with no permission. Therefore, I download the latest version of dhclient (4.1) from isc . you can get more information from here . Wish this helps. regards, Stanley Huang

[Level 3] How to debug python in run-time environment.

You can use pdb module to debug your python program in run-time environment in two ways. 1. import pdb module and set trace. e.g. #!/bin/env python import os, sys ... import pdb; pdb.set_trace() ... 2. use python command and import pdb module. $ python -m pdb ./myapp.py And about pdb useful commands: l: list source code b: break point r: run s: step: into function n: next: run next line c: : continue next loop where: where is the break point now ? help Ex. $ python -m pdb ./myapp.py (Pdb) l 1 #!/bin/env python 2 -> import os, sys 3 #print os.environ['PATH'] 4 os.environ['PATH']='/usr/bin:'+os.environ['PATH'] 5 #if './' not in sys.path: sys.path.append('./') 6 #if './lib' not in sys.path: sys.path.append('./lib') 7 #if '../lib' not in sys.path: sys.path.append('../lib') 8 exec_file = sys.argv[0] 9 os.chdir(os.path.dirname(sys.argv[0])) 10 ru

[Level 3] Open HA Cluster on OpenSolaris in VirtualBox.

There is a article to introduce Open HA Cluster with OpenSolaris in VirtualBox. Please refer to Open HA Cluster On OpenSolaris . Wish this helps. regards, Stanley Huang

[Level 3] How to use DTrace to trace java in OpenSolaris

http://www.solarisinternals.com/wiki/index.php/DTrace_Topics_Java Wish this helps. regards, Stanley Huang Publish Post

[Level 3] ZFS Evil Tuning on OpenSolaris

I saw a good artical about ZFS tuning , the link as following: http://www.solarisinternals.com/wiki/index.php/ZFS_Evil_Tuning_Guide Wish this helps. regards, Stanley Huang

[Level 3] ntfs support on CentOS 5.3

If you want to let your CentOS 5.3 support ntfs, you should install ntfs-3g package # yum install fuse fuse-ntfs-3g # modprobe fuse Wish this helps. regards, Stanley Huang

[Level 3] MySQL UDF for JSON

http://www.okpython.com/bbs/redirect.php?fid=9&tid=2889&goto=nextnewset Wish this helps. regards, Stanley Huang

[Level 3] Create LVM in Ubuntu.

Install LVM (Logical Volume Management) in Ubuntu. 1. Install LVM with apt-get # apt-get -y install lvm2 [Ref: http://www.debuntu.org/how-to-install-ubuntu-over-lvm-filesystem ] $ sudo mke2fs -j /dev/sda2 $ sudo pvcreate /dev/sda3 #create a physical volume on /dev/sda3 Physical volume "/dev/sda3" successfully created $ sudo vgcreate lvmvolume /dev/sda3 #create a volume group named lvmvolume using /dev/sda3 physical volume Volume group "lvmvolume" successfully created $ sudo lvcreate -n root -L 5G lvmvolume #create a logical volume of 5G named "root" in lvmvolume Logical volume "root" created $ sudo lvcreate -n home -L 10G lvmvolume #create a logical volume of 10G named "home" in lvmvolume Logical volume "home" created $ sudo lvcreate -n swap -L 2G lvmvolume #create a logical volume of 2G named "swap" in lvmvolume Logical volume "swap" created $ sudo mkfs -j /dev/lvmvolume/root -L r

[Level 3] Fix Windows7 MBR

bcdedit /export C:\BCD_Backup c: cd boot attrib bcd -s -h -r ren c:\boot\bcd bcd.old bootrec /RebuildBcd F8 -> repair -> command -> bootrec /fixmbr Wish this helps. regards, Stanley Huang

[Level 3] Networking library for Python -- Scapy.

One networking library for python called 'Scapy', is worth for you to try. http://www.secdev.org/projects/scapy/index.html Wish this helps. regards, Stanley Huang

[Level 1] Enable vim syntax for python.

If you want your vim support python syntax, you can do the following steps: 1. make directory. $ mkdir ~/.vim/syntax 2. Download python syntax profile from vim org. http://www.vim.org/scripts/script.php?script_id=790 3. enable syntax. $ cat ~/.vimrc syntax on Wish this helps. regards, Stanley Huang

[Level 3] How to implement unix password encryption with sha512 in Ubuntu.

#!/usr/bin/env python import crypt import re class shadowPassword: def __init__(self, shadow_file = '/etc/shadow'): self.shadowFile = shadow_file def getPasswordField(self, user): fd = open(self.shadowFile, 'r') for line in fd.readlines(): line = line.rstrip() match = re.match('^%s:([^:]*):.*$' % user, line) if match: return match.group(1) fd.close() return '' def setPasswordField(self, user): self.password_field = self.getPasswordField(user) def getPasswordEncryptType(self, password_field=''): if self.password_field: password_field = self.password_field return password_field.split('$')[1] def getPasswordSalt(self, password_field=''): if self.password_field: password_field = self.password_field return password_field.split('$')[2] def getEncryptPassword

[Level 1] Vim highlight search

If you want to search in vim, you can use the command '#' to select the word first. And if you want to hightlight it, you can set highlight search in ~/.vim.rc in ~/.vimrc set hlsearch Wish this helps. regards, Stanley Huang

[Level 2] How to highlight your code in blogspot.

Please refer to the following links: http://google-code-prettify.googlecode.com/svn/trunk/README.html http://stackoverflow.com/questions/1852537/how-to-use-prettify-with-blogger-blogspot example display for python code: #!/bin/env python class MyClass:   def __init__(self):   self.name = 'stanley'   self.age = 25 def getName(self):   return self.name def getAge(self):   return self.age if __name__ == '__main__':   man = MyClass()   print man.getName()   print man.getAge() Wish this helps. regards, Stanley Huang

[Level 3] Design Pattern in Python(1): Singleton

If you want to implement singleton in Python, you can refer the  following sample code. #!/usr/bin/env python c lass SingleFactory:     __single = None     def __init__( self ):         if not SingleFactory.__single:             SingleFactory.__single = self     def getInstance( self ):         return SingleFactory.__single if __name__ == '__main__':     f = SingleFactory()     a = f.getInstance()     b = f.getInstance()     print a     print b     a.count = 1     print a.count     print b.count Execute it. $ ./t.py <__main__.SingleFactory instance at 0x1004d1290> <__main__.SingleFactory instance at 0x1004d1290> 1 1 Wish this helps. regards, Stanley Huang

[Level 2] How to implement decorator in Python (I).

The sample of Python decorator (1, by class): #!/usr/bin/env python class my_de:   def __init__(self, f):     self.f = f   def __call__(self, *args, **kargs):     print 'Before you call the method (%s)' % self.f.__name__     self.f(*args, **kargs)     print 'After you call the method (%s)' % self.f.__name__ @my_de def helloworld(who, are, you):   print 'hello world! %s %s %s' % (who, are, you) if __name__ == '__main__':   helloworld('I', 'am', 'Stanley') Execute it. $ ./t.py Before you call the method (helloworld) hello world! I am stanley After you call the method (helloworld) The sample of Python decorator (2, by wrap function): #!/usr/bin/env python def my_de(f):   def new_f(*args, **kargs):     print 'Before you call the method (%s)' % f.__name__     f(*args, **kargs)     print 'After you call the method (%s)' % f.__name__   return new_f @my_de def helloworld(who, are, you):   pri

[Level 2] How to create Django project and apps by command mode.

How to create a Django project and apps by command mode, please follow the below commands: # django-admin.py startproject myProject # cd ./myProject # django-admin.py startapp myApp1 # cd ./myApp1 # python manage.py runserver [0.0.0.0:]8888 Wish this helps. regards, Stanley Huang

[Level 2] Implement static/class method in Python class.

You can use @staticmethod (decorator) to implement static method in Python class. #!/usr/bin/env python class de:   def __init__(self):     self.a = 1   def getA(self):     return self.a   @staticmethod   def getB():     return 2   @classmethod   def getCN():     return cls.__name__ if __name__ == '__main__':   d = de()   print 'd.getA() = %s' % d.getA()   print 'de.getB() = %s' % de.getB()   print 'classname of de = %s' % de.getCN()   print 'de.getA() = %s' % de.getA() Execute it. $ ./t.py de.getA() = 1 de.getB() = 2 classname of de = de Traceback (most recent call last):   File "./t.py", line 15, in     print 'de.getA() = %s' % de.getA() TypeError: unbound method getA() must be called with de instance as first argument (got nothing instead) Wish this helps. regards, Stanley Huang

How to setup your wireless interface to auto connect to ap in Ubuntu?

How to setup your wireless interface to auto connect to ap in Ubuntu? You can set the config in /etc/network/interface like below: wlan0 auto iface wlan0 inet dhcp wireless-essid your_essid wireless-key your_essid_passphrase wireless-channel your_essid_channel Wish this helps. regards, Stanley Huang

[Level 2] How to detect port with python script.

If you want to detect port, you can use socket module to do it. #!/bin/env python import os, sys import socket def detectPort(PORT):     # Echo server program     import socket     HOST = ''     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     try:         s.bind((HOST, PORT))         return_code=1     except:         return_code=0     s.close()     return return_code if __name__ == '__main__':   for PORT in [80,81,82,8000,8080,3306,3307]:     if detectPort(PORT): print PORT Wish this helps. regards, Stanley Huang

[Level 2] Python variable scope.

If you want to have a private property in Python class, you can add an prefix '__' before your variable. e.g. in ./lib/libcomm.py class common:     def __init__(self, name='stanley', age=25):         self.__name = name         self.__age = age         def setName(self, name):         self.__name = name         def getName(self):         return self.__name         def setAge(self, age):         self.__age = age         def getAge(self):         return self.__age  in ./test.py from lib.libcommon import * if __name__ == '__main__':     c = common('stanley', 24)     try:         print c.__age     except Exception, e:         print e     print c.getAge()     c.__age = 1     print c.__age     c.setAge(10)     print c.__age     print c.getAge() result: common instance has no attribute '__age' 24 1 1 10 Wish this helps. regards, Stanley Huang

[Level 2] How to compile .py to .pyc

How to compile .py to .pyc? Just use the module compileall Ex. # python -m compileall . or # python -m compileall ./t.py Wish this helps. regards, Stanley Huang

[Level 3] How to make your own python ide with vim.

There is a article for introduce how to make your own python ide with vim. Please refer to the following link: http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/ Wish this helps. regards, Stanley Huang

[Level 1] Remote UI display in local Ubuntu X.

If you want to display remote UI to your local X. You can use ssh -X to login remote server. Ex. local# ssh -X user@remote_host remote# echo $DISPLAY local_host:10.0 remote# xclock Then you can see xclock on your local X Wish this helps. regards, Stanley Huang

[Level 3] Knowing the Unix encrypt password.

Follow the below steps to know the encrypt password. 1. add new user " testpwd ": # useradd testpwd 2. set password to " mypass ": # passwd testpwd Enter new UNIX password: [ mypass ] Retype new UNIX password: [ mypass ] passwd: password updated successfully 3. get encrypt password: # grep ^ testpwd /etc/shadow testpwd :$ 6 $ qPApAmPP $ .EyjXo6y2NVpxrlng1r.OHiQi8XTC/PCFdQ22Y7cxfk5KlZu3DOxyNA3W.78jMYD.ipyJLoS1TH01/HuEBjBE0 :15037:0:99999:7::: PS. The meaning of the encrypt. $ id $ salt $ encrypted , string terminated by "$" ID | Method ────────────────────────────────────────────────── ─────── 1 | MD5 2a | Blowfish (not in mainline glibc; added in some Linux distributions) 5 | SHA-256 (since glibc 2.7) 6 | SHA-512 (since glibc 2.7) 4. get command "mkpasswd": # apt-get -y install mkpasswd 5. reproduce the encrypt password: # mkpasswd -m sha-512 mypass qPApAmPP $ 6 $ qPApAmPP $ .EyjXo6y2NVpxrlng1r.OHiQi8XTC/PCF

[Level 2] Handle with ctrl+c, ctrl+d in python script

If you want to handle ctrl+c, ctrl+d in your python script, you can catch KeyboardInterrupt and EOFError these two exception. The sample code as the following: #!/bin/env python import os, sys def disableCtrlD():     os.popen("stty eof '^C^D'").read() def enableCtrlD():     os.popen("stty eof '^D'").read() def testCD1():     while True:         try:             a = ''             a = raw_input('CLI(quit)> ')             if a == 'quit':                 break         except KeyboardInterrupt, e:             print e             print 'why you press ctrl+c'         except EOFError, e:             print e             print 'why you press ctrl+d'         except Exception, e:             print e def testCD2():     disableCtrlD()     while True:         try:             a = ''             a = raw_input('CLI(quit)> ')             if a == 'quit':