Posts

Showing posts from 2011

[Level 2] Package management in Python. (pip)

pip is a tool for installing and managing Python packages, you could find more info here Wish this helps. regards, Stanley Huang

[Level 2] MySQL security check with tcpdump.

you can check if MySQL data streams are encrypted or not by the following command: # tcpdump -l -i eth0 -w - src or dst port 3306 | strings Wish this helps. regards, Stanley Huang

[Level 3] Pythonbrew, the Python environment management tool.

The more info, please click here The Chinese resource from OpenFoundry, click here . Wish this helps. regards, Stanley Huang

[Level 3] Slides from Devoxx talk on Language / Library / VM Co-Evolution.

Slides from Devoxx talk on Language / Library / VM Co-Evolution, more info, please click here . Wish this helps. regards, Stanley Huang

[Level 3] The bonding info of Linux

The bonding info of Linux, click here for more detail. Wish this helps. regards, Stanley Huang

[Level 2] Pydoc, the document of Python.

In Java, we have javadoc to generate the document, in Python, we have pydoc. More info, please click here . The sample of pydoc as the following: The source code of testPyDoc.py #!/usr/bin/python """ This is a sample module to generate pydoc """ __author__ = 'Stanley Huang' __version__= '1.0' class PyDoc: """class docstrings""" def __init__ (self, user='guest', addr='Taipei'): """Set default attribute values only Keyword arguments: user -- name of user addr -- addr of user """ self.user = user self.addr = addr $ pydoc testPydoc Help on module testPyDoc: NAME testPyDoc - This is a sample module to generate pydoc FILE /tmp/testPyDoc.py CLASSES PyDoc class PyDoc | class docstrings | | Methods defined here: | | __init__(self, user='gues

[Level 3] How to implement AES in Python.

A paper for how to implement AES in Python. Please click here . Another paper is here . Wish this helps. regards, Stanley Huang

[Level 3] IoC/AOP in Python.

More Ioc info, please refer to here . More AOP info, please refer to here . Wish this helps. regards, Stanley Huang

[Level 2] How to update Ubuntu boot menu (grub).

If you want to modify grub menu of Ubuntu, you have following steps to do: 1. Modify default grub configuration file. # vi /etc/default/grub 2. Update grub configuration. # update-grub Generating grub.cfg ... Found linux image: /boot/vmlinuz-2.6.38-12-generic Found initrd image: /boot/initrd.img-2.6.38-12-generic Found linux image: /boot/vmlinuz-2.6.38-8-generic Found initrd image: /boot/initrd.img-2.6.38-8-generic Found memtest86+ image: /boot/memtest86+.bin Found Windows Recovery Environment (loader) on /dev/sda1 Found Windows 7 (loader) on /dev/sda2 done # More info. please refer to here . Wish this helps. regards, Stanley Huang

[Level 2] classmethod, staticmethod, abstractmethod decorators in Python.

#!/bin/env python from abc import * class p(object): __metaclass__ = ABCMeta @abstractmethod def printz(self): pass @abstractproperty def x(self): pass class o(p): def __init__(self, n=10): self._x = n def printX(self): print self._x def printx(self): print self.x @classmethod def printy(self): print self.x @staticmethod def printz(): print 'x' @property def x(self): return self._x @x.setter def x(self, times): self._x = self._x * times @x.getter def x(self): return self._x a = o(2) a.x = 5 print a.x a.printX() a.printx() a.printy() a.printz() #o.printX() # error #o.printx() # error o.printy() o.printz() $ ./t.py 10 10 10 <property object at 0x177a1b0> x <property object at 0x177a1b0> x Wish this helps. regards, Stanley Huang

[Level 1] Login server console with minicom on Ubuntu laptop.

If you want to use console to login server on Ubuntu laptop, you could try a useful app named "minicom". And you could download in by apt-get. # apt-get -y install minicom Wish this helps. regards, Stanley Huang

[Level 1] Get partition uuid on Ubuntu.

# blkid /dev/sda1: UUID="05580ede-bec4-44ae-b1a5-8e8c7b2e7c58" TYPE="ext4" /dev/sda2: UUID="3df58602-322b-437a-b65c-de21293f6840" TYPE="swap" /dev/sda5: UUID="5417e3d4-4b7d-4a79-a58a-a53cbeab6112" TYPE="ext4" Wish this helps. regards, Stanley Huang

[Level 1] Backup directories by cpio.

#!/bin/bash source=$1 target=$2 (cd $source; find . -print | cpio -ocv) | (cd $target; cpio -icuvd) # cd $source; find . -print | cpio -ocv > /tmp/tmp.cpio # cd $target; cpio -icuvd < /tmp/tmp.cpio Wish this helps. regards, Stanley Huang

[Level 2] Rock-Paper-Scissors

#!/bin/env python import random RPS = { 'Rock' : 1, 'Paper' : 2, 'Scissors' : 3 } if __name__ == '__main__': comRPS = random.choice(RPS.keys()) com = RPS[comRPS] youRPS = raw_input('Rock/Paper/Scissors: ') you = RPS[youRPS] print 'Com: %s' % comRPS print 'You: %s' % youRPS if com % len(RPS.keys()) + 1 == you: print 'You wins!' elif you % len(RPS.keys()) + 1 == com: print 'Com win!' else: print 'Break even!' Wish this helps. regards, Stanley Huang

[Level 2] map, reduce and filter methods in Python

#!/bin/env python a = [1,2,3,4,5,6,7,8,9] b = [1,2,3,4] c = [5,6,7,8] print filter(lambda x: x>5, a) print map(lambda x,y: x+y, b, c) print map(lambda x,y: bool(x) and bool(y), a, b) print map(lambda x,y: bool(x) or bool(y), b, a) print reduce(lambda x,y: x+y, a) $ /tmp/t.py [6, 7, 8, 9] [6, 8, 10, 12] [True, True, True, True, False, False, False, False, False] [True, True, True, True, True, True, True, True, True] 45 Wish this helps. regards, Stanley Huang

[Level 2] The sample of functools.partial() in Python.

#!/bin/env python import functools try: print int('10') ## equiv: print int('10', base=10) print int('10', 2) ## equiv: print int('10', base=2) int2 = functools.partial(int, 2) ## no default bonding parameter. print int2('10') ## fail, must assign the value of base int2 = functools.partial(int, base=2) ## set default base to 2 print int2('10') ## equiv: print int2('10', base=2) print int2('10', 10) ## fail, TypeError: keyword parameter 'base' was given by position and by name print int2('10', base=10) Wish this helps. regards, Stanley Huang

[Level 2] How to implement Enum in Python

#!/bin/env python class CreateRemove: Create = 1 Remove = 2 class AllowDeny: Allow = 1 Deny = 2 print CreateRemove.Create print AllowDeny.Deny Wish this helps. regards, Stanley Huang

[Level 1] Restrict user login in ssh.

You can use AllowUsers/AllowGroups/DenyUsers/DenyGroups in sshd_config to limit user login. e.g. # cat /etc/ssh/sshd_config AllowUsers user1 AllowGroups group1 DenyUsers user2 DenyGroups group2 Wish this helps. regards, Stanley Huang

[Level 2] How to execute super() in Python

If you want to use parent method in Python, you could use 'super()' method. But it only support new style class, therefore, you need to inherit 'object' class when you create your own class. e.g. #!/bin/env python import os, sys def new_style(): class NewSystemTools(object): def __init__(self): pass def runCmd(self, sCmd): return os.popen(sCmd).read() class MyNewSystemTools(NewSystemTools): def __init__(self): pass def runCmd(self, sCmd): return super(MyNewSystemTools, self).runCmd(sCmd) print '-- new style --' mnst = MyNewSystemTools() print mnst.runCmd('ls /') def old_style(): class SystemTools: def __init__(self): pass def runCmd(self, sCmd): return os.popen(sCmd).read() class MySystemTools(SystemTools): def __init__(self): pass

[ Level 2] How to dump object to file in Python

#!/bin/env python import os, sys import marshal a = [1,2,3] fd = open('/tmp/t.log', 'wb') marshal.dump(a, fd) fd.close() fd = open('/tmp/t.log', 'rb') b = marshal.load(fd) for i in b: print i fd.close() Wish this helps. regards, Stanley Huang

[Level 2] Vim autocomplete for python.

If you want to use vim to writing python script. You could download vim autocomplete for python from here And then, you could put pythoncomplete.vim in ~/.vim/autoload/ When you writing python, you could use ctrl+p to autocomplete python syntax. Wish this helps. regards, Stanley Huang

[Level 1] Useful vim environment settings.

My current vim settings are below. You could get more sample in here . set nu set ic :au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif set nosmartindent set tabstop=4 set shiftwidth=4 set expandtab set hlsearch syntax on " filetype indent plugin on set background=dark set modeline " filetype indent on " au FileType python setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4 " au FileType python setlocal ts=8 et sw=4 sts=4 set nobackup set noswapfile set showmode set ruler map j gj map k gk< " auto trim tailing spaces autocmd BufWritePre *.py :%s/\s\+$//e " folding set foldenable set foldmethod=syntax set foldcolumn=0 nnoremap @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo') " auto command autocmd BufRead *.py nmap :w !python % autocmd FileType java map :!javac "%:p" &&am

[Level 1] Encoding in Python script.

If there are some wording not for ascii, you should add # -*- coding: (encoding) -*- to prevent compile error. example error message: File "./testEncoding.py", line 21 SyntaxError: Non-ASCII character '\xe6' in file ./testForLoop_2.6.py on line 21, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details e.g. #!/usr/bin/python2.6 # -*- coding: utf8 -*- ### chinese testing slang="有嘴說別人無嘴說自己" sword="嘴" ## error with encoding #for i in slang: # print i # use python shell to display encoding # ex. # >>> "有嘴說別人無嘴說自己" # '\xe6\x9c\x89\xe5\x98\xb4\xe8\xaa\xaa\xe5\x88\xa5\xe4\xba\xba\xef\xbc\x8c\xe7\x84\xa1\xe5\x98\xb4\xe8\xaa\xaa\xe8\x87\xaa\xe5\xb7\xb1\xe3\x80\x82' # >>> "嘴" # '\xe5\x98\xb4' l=len(sword) h=0 k=0 count=0 for item in slang: k=0 f=1 while k<l: if slang[h+k]==sword[k]: k+=1 continue else: f=0 break if f==1:

[Level 1] Install telnetd in Ubuntu 10.04

Install telnetd in Ubuntu 10.04: # sudo su # apt-get install openbsd-inetd # echo "telnet stream tcp nowait root /usr/sbin/tcpd /usr/sbin/in.telnetd" >> /etc/inetd.conf # /etc/init.d/openbsd-inetd restart Wish this helps. regards, Stanley Huang

[Level 3] More decorator samples.

There is a good website to demo decorator sample codes. here ''' Usage: @deprecated def func(): ... ''' class deprecated: def __init__(self, func): self.func = func self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__ self.__dict__.update(self.func.__dict__) pass """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def __call__(self, *args, **kwargs): msg = "Call to deprecated function %s()." % self.func.__name__ ## Suppressing Warnings warnings.simplefilter("ignore") warnings.warn(msg, category=DeprecationWarning) ## Delete ignore filter del warnings.filters[0] (tmpDebug2Console, libcommon.bDebug2Console) = (libcommon.bDebug2Console, False) libcommon.debug(msg, logfile='de

[Level 1] Compile python scripts.

If you want to compile python script manually, you could use following command. $ python -c "import compileall; compileall.compile_dir('./', force=1)" Wish this helps. regards, Stanley Huang

[Level 2] enumrate() in Python.

#!/bin/env python aWeek = ['Sun', 'Mon','Tue','Wed', 'Thu', 'Fri', 'Sat'] ## without enumerate() print 'without enumerate()...' index = 0 for day in aWeek: print index, day index += 1 ## without enumerate() print 'without enumerate()...' for index in range(len(aWeek)): print index, aWeek[index] ## with enumerate() print 'with enumerate()...' for (index, day) in enumerate(aWeek): print index, day without enumerate()... 0 Sun 1 Mon 2 Tue 3 Wed 4 Thu 5 Fri 6 Sat without enumerate()... 0 Sun 1 Mon 2 Tue 3 Wed 4 Thu 5 Fri 6 Sat with enumerate()... 0 Sun 1 Mon 2 Tue 3 Wed 4 Thu 5 Fri 6 Sat Use enumerate() would make code easier to read. Wish this helps. regards, Stanley Huang

[Level 2] Python Decorator Sample.

Another sample for Python decorator. #!/usr/bin/env python class ServiceFee: def __init__(self, f): self.f = f pass def __call__(self, *args, **kargs): return self.f(*args, **kargs)*1.1 class TaxFee: def __init__(self, f): self.f = f pass def __call__(self, *args, **kargs): return self.f(*args, **kargs)*1.05 @ServiceFee @TaxFee def beef(pricePerKG, KG): return pricePerKG*KG print 'Beef $10/KG, and buy 5KG=%s' % beef(10, 5) print 'Beef $20/KG, and buy 10KG=%s' % beef(20, 10) $ ./t.py Beef $10/KG, and buy 5KG=57.75 Beef $20/KG, and buy 10KG=231.0 Wish this helps. regards, Stanley Huang

[Level 2] Join lines by sed commands.

If you want to join lines in shell script, you could use sed command. #!/bin/bash cat > /tmp/t.txt <<EOF eth0 eth1 eth2 eth3 eth4 eth5 eth6 lo0 EOF sed -e :a -e '$!N; s/\n/,/; ta' /tmp/t.txt $ ./joinLinesBySed.sh eth0,eth1,eth2,eth3,eth4,eth5,eth6,lo0 Wish this helps. regards, Stanley Huang

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

Months ago, I wrote a simple decorator, without decorator parameters, implement in Python. [Level 2] How to implement decorator in Python (I). Now, I'll show you how to implement decorator with parameter. The sample of Python decorator (1, by class): #!/bin/env python class Decorator: def __init__(self, man, woman): self.man = man self.woman = woman pass def __call__(self, f): def wrapped_f(*args, **kargs): print 'hello %s' % self.man f(*args, **kargs) print 'world %s' % self.woman return wrapped_f @Decorator('stanley', 'christy') def test(who): print 'test(%s)' % who test('joseph') $ ./test.py hello stanley test(joseph) world christy The sample of Python decorator (2, by wrap function): #!/bin/env python def Decorator(man, woman): def wrap(f): def wrapped_f(*args, **kargs): print 'hello %s' % man

[Level 2] Testing combination of loop and try.

Sample code and test result are as the following: #!/bin/env python class e(Exception): def __init__(self): pass server_list = [1,2,3,4,5] for server in server_list: try: sReturn = server print 's:%s' % sReturn if sReturn<3: continue if sReturn==3: raise e print 'try:%s' % sReturn except Exception, e: print 'except1:%s' % sReturn continue print 'except2:%s' % sReturn else: print 'else:%s' % sReturn break finally: print 'finally:%s' % sReturn $ ./t.py s:1 finally:1 s:2 finally:2 s:3 except1:3 finally:3 s:4 try:4 else:4 finally:4 Wish this helps. regards, Stanley Huang

[Level 1] Make Nautilus always use Location Entry in Ubuntu 10.04

Hi all: FYI. http://ubuntuguide.net/make-nautilus-always-use-location-entry-in-ubuntu-10-04 Wish this helps. regards, Stanley Huang

[Level 1] Install autoexpect

$ autoexpect -f ./auto.exp autoexpect started, file is ./auto.exp $ ssh stanley@localhost The authenticity of host 'localhost (127.0.0.1)' can't be established. RSA key fingerprint is 36:12:a4:49:26:fe:18:0d:77:bf:c7:e8:36:86:b7:f2. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'localhost' (RSA) to the list of known hosts. stanley@localhost's password: Welcome to Ubuntu 11.04 (GNU/Linux 2.6.38-10-generic x86_64) * Documentation: https://help.ubuntu.com/ *** /dev/sda5 will be checked for errors at next reboot *** Last login: Thu Jul 28 12:17:50 2011 from stanley-ubuntu $ ls apache-cassandra-0.8.1-SNAPSHOT.jar Public auto.exp Rock Desktop script.exp Documents scripts Downloads scripts_20110302.tgz eclipse Self_assesment_201103.pdf English_Survey.pdf SUR-1-Vesu_Pi

[Level 2] How to simulate udevinfo in Ubuntu 11.04

When you try to use command udevinfo in Ubuntu 11.04, you would get the response "udevinfo: command not found". How to simulate the command udevinfo? Use command udevinfo with info option. Ex. # udevadm info -q all -n /dev/video0 You could also create a function named udevinfo as you like Ex. # udevinfo () { udevadm info -a -p `udevadm info -q path -n "$1"`; } # udevinfo /dev/video0 ... Wish this helps. regards, Stanley Huang

[Level 2] python oui lookup

$ sudo apt-get -y install python-netaddr ... $ cd /usr/share/pyshared/netaddr/eui $ sudo python ./ieee.py downloading latest copy of http://standards.ieee.org/regauth/oui/oui.txt downloading latest copy of http://standards.ieee.org/regauth/oui/iab.txt $ python >>> from netaddr import * >>> mac = EUI('bc:ae:c5:3b:fc:5e') >>> print mac.oui.registration().org ASUSTek COMPUTER INC. Wish this helps. regards, Stanley Huang

[Level 2] Use expect to run openvpn.

#!/usr/bin/expect set password [lindex $argv 0] spawn sudo openvpn --script-security 2 --config /home/stanley/VPN/MyVPN_config/MyVPN.ovpn expect Enter\ Private\ Key\ Password: sleep 1 send $password sleep 1 interact Test run: # ./openvpn.expect mypassword Wish this helps.  regards, Stanley Huang

[Level 2] Pexpect of Python.

#!/bin/env python import os, sys import StringIO class AuthorizedKeyError(Exception): def __init__(self, host): self.value = 'Did not be authorized by remote server(%s)!!!' % host def __str__(self): return repr(self.value) class FileSyncManager: def fileSync(self, user, host, file): output = StringIO.StringIO() sCmd = 'scp %s %s@%s:%s' % (file, user, host, file) self.debug(sCmd) scp = pexpect.spawn(sCmd) scp.logfile = output while True: index = scp.expect(["Are you sure you want to continue connecting (yes/no)?", "password:" ,pexpect.TIMEOUT, pexpect.EOF]) if index == 0: scp.sendline('yes') elif index == 1: raise AuthorizedKeyError(host) else: break if scp.exitstatus: error_message = outpu

[Level 2] How to skip StrictHostKeyChecking in ssh.

If you want to ignore strict host key checking, even skip saving the host key info, you could use option UserKnownHostsFile, StrictHostKeyChecking. Ex. ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no stanley@192.168.1.1 or modify /etc/ssh/ssh_config for global settings. # cat /etc/ssh/ssh_config ... UserKnownHostsFile /dev/null StrictHostKeyChecking no ... Wish this helps. regards, Stanley Huang

[Level 2] Recursive directory list

#!/bin/env python import os, sys wholeFileList = [] baseDir = sys.argv[1] for parentDir, childDirList, fileList in os.walk(baseDir): for file in fileList: wholeFileList.append(os.path.join(parentDir,file)) for file in wholeFileList: print file # ./t.py /tmp/d /tmp/d/1.txt /tmp/d/2/6.txt /tmp/d/2/3/a.txt /tmp/d/2/4/b.txt /tmp/d/2/5/c.txt Wish this helps. regards, Stanley Huang

[Level 3] Python performance.

Days ago, I discussed the coding style of python, and I use one example to present what I want you to know. The most 2 ways to use of renaming a file are: 1. Use rename method os moudle [ os.rename(f1, f2) ], 2. Use external command by popen method[ os.popen('mv f1 f2') ]. Some people might think there are not much different between these two ways. But after a stress test, you will realize it did has different between these two ways. The sample code and test run are as the following. #!/bin/env python import os, sys from time import gmtime, strftime n = 10000 f1 = '/1' f2 = '/2' os.popen('touch %s' % f1).read() print strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) for i in range(n): if os.path.exists(f1): os.rename(f1, f2) else: os.rename(f2, f1) print strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) for i in range(n): if os.path.exists(f1): os.popen('mv %s %s' % (f1, f2))

[Level 3] Python performance tips.

Python performance tips. http://wiki.python.org/moin/PythonSpeed http://wiki.python.org/moin/PythonSpeed/PerformanceTips Wish this helps. regards, Stanley Huang

[Level 2] How to get python version on run-time.

#!/bin/env python import sys print sys.version # python -c 'import sys; print sys.version' 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] Wish this helps. regards, Stanley Huang

[Level 2] How to allow using symbolic link in tomcat? (with python code)

If you want to allow using symbolic link in tomcat, you could add and attribute called "context" with an key "allowLinking" eg. <Context path="/myapp" allowLinking="true"/> and I wrote a sample python code to do this. #!/bin/env python import os,sys from xml.dom import minidom def getXMLDom(FILE): return minidom.parse(open(FILE,'r')) def saveXML(FILE, dom): fd = open(FILE, 'w') fd.write(dom.toxml()) fd.close() def appendElement(FILE, base_element_name, element_name, attr_key_val, element_index=0, backup_flag='y'): if backup_flag == 'y': backupConfigFile(FILE) dom = getXMLDom(FILE) e = dom.createElement(element_name) for attr, val in attr_key_val: e.setAttribute(attr, val) dom.getElementsByTagName(base_element_name)[element_index].appendChild(e) saveXML(FILE, dom) xmlFile = prefix+'/opt/ruckuswireless/3rdparty/tomcat/conf/server.xml' base_element_

[Level 1] How to install Jython on Ubuntu.

You have two way to install jython on Ubuntu: 1. Use apt-get: # sudo apt-get -y install jython # jython --version 2. Download source: # cd /tmp # wget http://sourceforge.net/projects/jython/files/jython/2.5.2/jython_installer-2.5.2.jar/download # mv ./download ./jython.jar # java -jar ./jython.jar ... following the wizard. # export PATH=$PATH:/opt/jython/bin # (if you installed Jython in /opt/jython) # jython --version Wish this helps. regards, Stanley Huang

[Level 1] How to install Scala on Ubuntu.

You have two way to install it. 1. Use apt-get: # sudo apt-get -y install scala 2. Download source: (browse http://www.scala-lang.org/downloads first) # cd /opt # wget http://www.scala-lang.org/downloads/distrib/files/scala-2.9.0.1.tgz # tar -C /opt zxf ./scala-2.9.0.1.tgz # export PATH=$PATH:/opt/scala-2.9.0.1/bin # scala -version Wish this helps. regards, Stanley Huang

[Level 2] Enable wireless of network-manager in Ubuntu 11.04

Once you upgrade Ubuntu from 10.04 to 11.04, and you will find out the network-manager won't manage wireless any more. But you still could change NetworkManager.conf to enable it. # sudo vi /etc/NetworkManager/NetworkManager.conf and change "managed" attribute from "false" to “true“ and restart it. # sudo /etc/init.d/network-manager restart Wish this helps. regards, Stanley Huang

[Level 1] How to set ntp client in Ubuntu.

If you want to sync time with time server in Ubuntu, you could use command ntpdate + time_server. And don't forget write date into bios too. ntpdate time.stdtime.gov.tw && hwclock -w Wish this helps. regards, Stanley Huang

[Level 1] How to grep in file.

Just use -P and '\t' with grep command. Ex. # grep -P '\t' /etc/passwd Wish this helps. regards, Stanley Huang

[Level 1] MP3 editor in Ubuntu.

If you want to modify mp3 in Ubuntu, you could use "audacity". And you could download it from reposity. The commands as the following. # apt-cache search audacity create-resources - shared resources for use by creative applications audacity - fast, cross-platform audio editor audacity-data - fast, cross-platform audio editor (data) audacity-dbg - fast, cross-platform audio editor (debug) vamp-plugin-sdk - audio analysis and feature extraction plugins (SDK) # apt-get -y install audacity After for a while, I heard a good tool to convert mp4 to mp3 call avidemux # apt-cache search avidemux libavidemux0 - a free video editor - shared libraries avidemux - a free video editor - GTK version avidemux-cli - a free video editor - command line version avidemux-common - a free video editor - Internationalization files avidemux-plugins-cli - a free video editor - CLI plugins avidemux-plugins-common - a free video editor - common files for plugins avidemux-plugins-gtk - a free video

[Level 1] Linux simulator on web.

Petty cool stuff. Linux simulator on web. Please refer to the foll http://bellard.org/jslinux Wish this helps. regards, Stanley Huang

[Level 2] How to check the resource limitation of specific process in Ubuntu.

How to check the resource limitation of specific process in Ubuntu. You can follow the below steps: # ps -ef | grep nfsd4 root 1098 2 0 May13 ? 00:00:00 [nfsd4] root 18674 18607 0 20:32 pts/15 00:00:00 grep --color=auto nfsd4 # cat /proc/1098/limits Limit Soft Limit Hard Limit Units Max cpu time unlimited unlimited seconds Max file size unlimited unlimited bytes Max data size unlimited unlimited bytes Max stack size 10485760 unlimited bytes Max core file size 0 unlimited bytes Max resident set unlimited unlimited bytes Max processes 47490 47490 processes Max open files 1024 1024 files Max locked m

[Level 2] How to connect wireless ap by command in Ubuntu.

How to connect wireless ap by command in Ubuntu? You can use two commands, 'iwlist', 'iwconfig'. # iwlist --help Usage: iwlist [interface] scanning [essid NNN] [last] [interface] frequency [interface] channel [interface] bitrate [interface] rate [interface] encryption [interface] keys [interface] power [interface] txpower [interface] retry [interface] ap [interface] accesspoints [interface] peers [interface] event [interface] auth [interface] wpakeys [interface] genie [interface] modulation # iwlist wlan0 scanning essid ap_name # iwconfig --help Usage: iwconfig [interface] interface essid {NNN|any|on|off} interface mode {managed|ad-hoc|master|...} interface freq N.NNN[k|

[Level 1] How to get user home directoy in Python

#!/bin/env python import os print os.path.expanduser('~') print os.path.expanduser('~stanley') print os.environ['HOME'] ./getUserHomeDirectory.py /home/stanley /home/stanley /home/stanley Wish this helps. regards, Stanley Huang

[Level 1] How to setup Cassandra home directory

If you want to create multi Cassandra instances and only use one copy of binary. You need to setup CASSANDRA_HOME environment variable. If you only use symbolic link to link binary file, Cassandra will search the real binary directory and set its parent directory as the home, if you don't setup the CASSANDRA_HOME environment variable. # export CASSANDRA_HOME=[new directory you want] # cd [new directory you want] # ./bin/cassandra Wish this helps. regards, Stanley Huang

[Level 2] how to extract compressed file in Python.

If you want to extract compressed file, you could use zipfile/tarfile to implement. [zip] #!/bin/env python import sys, zipfile, os, os.path def unzip_file_into_dir(file, dir): os.mkdir(dir, 0777) zfobj = zipfile.ZipFile(file) for name in zfobj.namelist(): if name.endswith('/'): os.mkdir(os.path.join(dir, name)) else: outfile = open(os.path.join(dir, name), 'wb') outfile.write(zfobj.read(name)) outfile.close() unzip_file_into_dir('/tmp/mywar.war', '/tmp/mywar') [tar.gz] #!/bin/env python import tarfile def extract_file(file_name): tar_file=tarfile.open(name=file_name, mode='r:gz') tar_file.extractall() tar_file.close() pass extract_file('/tmp/mytar.tar.gz') Wish this helps. regards, Stanley Huang

[Level 2] Convert keys between openssh and openssl

A good artical for convert keys between openssh and openssl. http://sysmic.org/dotclear/index.php?post/2010/03/24/Convert-keys-betweens-GnuPG,-OpenSsh-and-OpenSSL Wish this helps. regards, Stanley Huang

[Level 2] How to create multi instances of tomcat.

If you want to create multi instances of tomcat, you can follow the below steps: 1. Copy logs, conf and webapps from origianl tomcat foler to a new location. # mkdir -p [a new folder you like] # cd [original tomcat folder] # cp ./logs ./conf ./webapps [a new folder you like] 2. Set environment variables "CATALINA_BASE" to the above path. # export CATALINA_BASE=[a new folder you like] 3. Startup tomcat. # [original tomcat folder]/bin/startup.sh And what's the difference between CATALINA_BASE and CATALINA_HOME, the decision path is as below: 1. Decide CATALINA_BASE: If you have CATALINA_BASE, the base directory is CATALINA_BASE, if not, the real path of binary would be the CATALINA_BASE. 2. Decide CATALINA_HOME: If you have CATALINA_HOME, the webapps base directory is in CATALINA_HOME, if not, the CATALINA_BASE would be the CATALINA_HOME. Wish this helps. regards, Stanley Huang

[Level 2] How to display current line number in Python

If you want to display current line number for debug info. You can import inspect to do that. #!/bin/env python import inspect from inspect import currentframe, getframeinfo def getFilenameLineno(): frameinfo = getframeinfo(currentframe().f_back) return (frameinfo.filename, frameinfo.lineno) def lineno(): return inspect.currentframe().f_back.f_lineno def curr_filename_lineno(): return inspect.currentframe().f_back.f_code if __name__ == '__main__': print lineno() # skip line with comment print curr_filename_lineno() print '%s(#%s)' % getFilenameLineno() print lineno() $ ./testLineno.py 16 <code object <module> at 0xb7509f50, file "/tmp/t.py", line 2> /tmp/testLineno.py(#20) 22 Another way is to parse inspect.stack() e.g. #!/bin/env python import inspect def t(): tt() def tt(): ttt() def ttt(): tttt() def tttt(): print inspect.stack() if __name__ == '__main__': t()

[Level 2] How to use yield in Python

yield in python just pass the control to the parent. if a() call b(), in b and execute yield, the control would back to a() util a call generator.next() e.g. #!/bin/env python def foo(): print 'start foo()' ## only pass here when first time call .next() n = 3 for i in range(1,n+1): print 'in for()' print 'yield %s' % i yield i ## return i when call .next() print 'back to for()' ## start from here when call .next() again if __name__ == '__main__': print 'start main' print 'init main vars' f = foo() i = 0 n = 10 print 'f: %s' % f print 'i: %s' % i print 'n: %s' % n for x in range(0,n): print 'f.next()' i = f.next() print 'print i' print i print 'in main' print 'call again f.next()' print f.next() print 'ex

[Level 1] Support utf-8 in python.

If you got an error message like "SyntaxError: Non-ASCII character '\xe4' in file" That means you have non-ascii character in your script. And if you want to support utf-8, you could add the comment in your script. e.g. #!/bin/env python # -*- coding: utf8 -*- Wish this helps. regards, Stanley Huang

[Level 3] Unit test in Python.

#!/usr/bin/env python import os,sys import unittest class C(object): def __init__(self): self.name = 'stanley' self.age = 24 class TS(unittest.TestCase): ## set up def setUp(self): self.c = C() pass ## clean up def tearDown(self): pass def test_getName(self): print self.c.name def test_getAge(self): print self.c.age def test_getNameAge(self): c = C() print c.name print c.age def runTest(self): print self.test_getName() print self.test_getAge() #def myTestModule(): # tests = ['test_getName', 'test_getAge'] # suite = unittest.TestSuite(map(TS, tests)) # unittest.TextTestRunner(verbosity=2).run(suite) class TS1(unittest.TestCase): def setUp(self): self.c = C() pass def tearDown(self): pass def test_name1(self): print self.c.name def test_age1(self):

[Level 2] Python variable scope (2).

In previous, I wrote a paper for python variable scope . This time, I try to use python native decorator to implement the same idea. #!/usr/bin/env python class C(object): def __init__(self): self._name = None self.__age = None @property def name(self): """I'm the 'name' propertage.""" return self._name @name.setter def name(self, value): self._name = value @name.deleter def name(self): del self._name @property def age(self): pass @age.getter def age(self): return self.__age @age.setter def age(self, value): self.__age = value if __name__ == '__main__': c = C() c.name = 1 print c.name print c._name del c.name try: print c.name except AttributeError, e: #print "'C' object has no attribute '_name'" print e c.age = 2

[Level 3] Firewall in Ubuntu.

install gui tool for ufw # apt-get -y install gufw # gufw use command(ufw) to setting firewall, and the config file in in /lib/ufw/user.rules # ufw deny from any to any port 22 # ls -al /lib/ufw/user.rules -rw-r----- 1 root root 1405 2011-04-01 17:36 /lib/ufw/user.rules # ufw delete deny from any to any port 22 # ls -al /lib/ufw/user.rules -rw-r----- 1 root root 1263 2011-04-01 17:36 /lib/ufw/user.rules my setting history (reference only): ufw disable ufw default deny ufw logging ON ufw enable ufw allow 22/tcp ufw allow proto tcp from 192.168.1.0/24 to 192.168.1.101 port 80 use iptables command: #!/bin/bash MY_IP=192.168.100.101 # Flushing all rules and chains iptables -F iptables -X # Setting default policy iptables -P INPUT DROP iptables -P OUTPUT ACCEPT iptables -P FORWARD DROP # Allow traffic on loopback iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT # Allow ssh for in/out iptables -A INPUT -p tcp -s 0/0 -d $MY_IP --sport 513:65535 --dport 22 -m state

[Level 2] How to compare two list (array) in Python

#!/bin/env python a=[1,2,3] b=[2,3,4] set_a = set(a) set_b = set(b) print set_a.difference(set_b) print set_b.difference(set_a) print set_a.union(set_b) print set_a.intersection(set_b) # print set_a.difference(set_b)[0] ## fail, 'set' object does not support indexing print list(set_a.difference(set_b))[0] $ ./t.py set([1]) set([4]) set([1, 2, 3, 4]) set([2, 3]) 1 Wish this helps. regards, Stanley Huang

[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