Posts

Showing posts from April, 2011

[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