<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Admon Home &#187; python</title>
	<atom:link href="http://www.admon.org/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.admon.org</link>
	<description>Linux System Administration</description>
	<lastBuildDate>Sat, 19 May 2012 03:36:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Limit the size of Subversion commitment</title>
		<link>http://www.admon.org/limit-the-size-of-subversion-commitment/</link>
		<comments>http://www.admon.org/limit-the-size-of-subversion-commitment/#comments</comments>
		<pubDate>Wed, 23 Nov 2011 16:09:40 +0000</pubDate>
		<dc:creator>joseph</dc:creator>
				<category><![CDATA[Applications]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[subversion]]></category>

		<guid isPermaLink="false">http://www.admon.org/?p=985</guid>
		<description><![CDATA[Has your subversion repository ever been abused by massive commitments? If not, I should say that you are lucky. Never mind that someday you might be abused as it&#8217;s hard to predict what the non-Ops are working on and trying to do. It would suck just because some people were committing large files without any [...]]]></description>
			<content:encoded><![CDATA[<p>Has your <a title="subversion" href="http://subversion.tigris.org" target="_blank">subversion</a> repository ever been abused by massive commitments?<br />
If not, I should say that you are lucky. Never mind that someday you might be abused as it&#8217;s hard to predict what the non-Ops are working on and trying to do.<span id="more-985"></span><br />
It would suck just because some people were committing large files without any legitimate reasons. There are other annoying consequences. Your daily backup would take longer time to finish eating more disk space, and your commitment analysis tool would get hiccups like ours.</p>
<p>So, <strong>How can we limit the size of a Subversion commitment?</strong><br />
The solution is quite easy, use the <a href="http://svnbook.red-bean.com/en/1.6/svn-book.html#svn.ref.reposhooks.pre-commit" target="_blank">pre-commit hook</a>. You can find some examples after searching around. Here&#8217;s the script that I use. It reads the tmp files in <em>db/transactions/</em>, caculate the total size and compare it with your settings (<em>db/tranactions</em> only saves changesets, not original files).</p>
<p>If the size exceeds your limit, the commitment fails and user will be warned with details.</p>
<pre>#!/usr/bin/env python
#
# Limit the size of SVN commits. It reads db/transactions to caculate commit size.
# Put the follwoing 3 lines in hook/pre-commit hook like this:
#
# REPOS="$1"
# TXN="$2"
# check_commit_size.py "$REPOS" "$TXN" || exit 1
#

import sys,os,popen2

# The size is not an exact value.
MAX_BYTES = 10000000

def printUsage():
    sys.stderr.write('Usage: %s "$REPOS" "$TXN" ' % sys.argv[0])

def getTransactionSize(repos, txn):
    txnRevPath = repos+'/db/transactions'+'/'+txn+'.txn'+'/rev'
    return os.stat(txnRevPath)[6]

def checkTransactionSize(repos, txn):
    size = getTransactionSize(repos, txn)
    if (size &gt; MAX_BYTES):
        sys.stderr.write("Sorry, you are trying to commit %d bytes, which is larger than the limit of %d.\n" % (size, MAX_BYTES))
        sys.stderr.write("If you think you have a good reason to, email to Ops and ask for permission.")
        sys.exit(1)

if __name__ == "__main__":
    #Check that we got a repos and transaction with this script
    if len(sys.argv) != 3:
        printUsage()
        sys.exit(2)
    else:
        repos = sys.argv[1]
        txn = sys.argv[2]

    checkTransactionSize(repos, txn)</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.admon.org/limit-the-size-of-subversion-commitment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: initialize a list</title>
		<link>http://www.admon.org/python-initialize-a-list/</link>
		<comments>http://www.admon.org/python-initialize-a-list/#comments</comments>
		<pubDate>Sun, 16 Oct 2011 00:42:36 +0000</pubDate>
		<dc:creator>joseph</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.admon.org/?p=951</guid>
		<description><![CDATA[I met this issue last week, and finally got a proper way to handle it. We normally init a list like this &#8220;list=[]&#8220;, then how can we initialize a python list with a string variable? Here&#8217;s my example. We created a list &#8220;a&#8221; and its initial value is ["abc"]: Macbook-pro:~ joseph$ python Python 2.6.1 (r261:67515, [...]]]></description>
			<content:encoded><![CDATA[<p>I met this issue last week, and finally got a proper way to handle it.</p>
<p>We normally init a list like this &#8220;<em>list=[]</em>&#8220;, then how can we initialize a python list with a string variable?<span id="more-951"></span></p>
<p>Here&#8217;s my example. We created a list &#8220;a&#8221; and its initial value is <em>["abc"]</em>:</p>
<pre>Macbook-pro:~ joseph$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; a
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'a' is not defined
&gt;&gt;&gt; try:
...  a.append("abc")
... except NameError:
...  a="abc".split()
...
&gt;&gt;&gt; a
['abc']
&gt;&gt;&gt; try:
...  a.append("abc")
... except NameError:
...  a="abc".split()
...
&gt;&gt;&gt; a
['abc', 'abc']</pre>
<p>Python is so wonderful, and I&#8217;m just a python beginner..</p>
]]></content:encoded>
			<wfw:commentRss>http://www.admon.org/python-initialize-a-list/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Query domain name whois info by Python</title>
		<link>http://www.admon.org/query-domain-name-whois-info-by-python/</link>
		<comments>http://www.admon.org/query-domain-name-whois-info-by-python/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 06:21:58 +0000</pubDate>
		<dc:creator>joseph</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[whois]]></category>

		<guid isPermaLink="false">http://planet.admon.org/?p=890</guid>
		<description><![CDATA[In one of our former post, we give an example on how to query IP whois info by Python, here is an example on how to query whois information for a domain name. #!/usr/bin/python #encoding = utf8 #Author:hysia import sys import socket PORT = 43 WhoisServers = {'com':'whois.internic.net', 'net':'whois.internic.net', 'org':'whois.pir.org', 'nfo':'whois.afilias.info', 'biz':'whois.biz', '.cc':'whois.nic.cc', 'edu':'rs.internic.net', 'mil':'whois.nic.mil', [...]]]></description>
			<content:encoded><![CDATA[<p>In one of our former post, we give an example on how to <a title="Query IP whois info" href="http://planet.admon.org/query-ip-whois-info-in-python/" target="_blank">query IP whois info by Python</a>, here is an example on how to query whois information for a domain name.</p>
<pre>#!/usr/bin/python
#encoding = utf8<span id="more-890"></span>
#Author:hysia

import sys
import socket

PORT  =  43
WhoisServers = {'com':'whois.internic.net',
              'net':'whois.internic.net',
              'org':'whois.pir.org',
              'nfo':'whois.afilias.info',
              'biz':'whois.biz',
              '.cc':'whois.nic.cc',
              'edu':'rs.internic.net',
              'mil':'whois.nic.mil',
              'gov':'whois.nic.gov',
              '.uk':'whois.nic.uk',
              '.us':'whois.nic.us',
              'ame':'whois.nic.name',
              'eum':'whois.museum',
              '.su':'whois.ripn.net',
              '.ru':'whois.nic.ru',
              'int':'whois.iana.org',
              '.ws':'whois.worldsite.ws',
              '.kr':'whois.krnic.net',
              '.jp':'whois.nic.ad.jp',
              '.it':'whois.nic.it',
              '.de':'whois.denic.de',
              '.fr':'whois.nic.fr',
              '.ca':'whois.cira.ca',
              '.cn':'whois.cnnic.net.cn',
              '.tw':'whois.twnic.net.tw',
              '.hk':'whois.hkdnr.net.hk',
              '.au':'whois.aunic.net',
              '.ac':'whois.nic.ac',
              'DEF':'whois.verisign-grs.com'}
              #'DEF':'whois.apin.net'}

fulldomain = sys.argv[1]

if fulldomain.startswith('www.'):
    fulldomain = fulldomain[4:]

domain = fulldomain[-3:]
print 'Domain: ',fulldomain
if not WhoisServers.get(domain):
    whoisserver = WhoisServers['DEF']
else:
    whoisserver = WhoisServers[domain]
print whoisserver

try:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((whoisserver,PORT))
    s.send(fulldomain + "\r\n")
    response = ''

    while True:
        data = s.recv(4096)
        response += data
        if data == '':
            break
    s.close()
    infomation = response.lower()
    try:
        pos = infomation.find('expiration date: ')
        expirDate = infomation[pos+17:pos+28]
        print 'Expiration Date:',expirDate
    except:
        print 'unkown'

except:
    print 'time out'
</pre>
<p>Looks smart! But never mind that the whois info cannot be returned correctly sometimes. I haven&#8217;t got time to look into this limitation.<br />
The script is copied from here: <a rel="external" href="http://blog.hysia.com/2010/03/25/python-whois.html">http://blog.hysia.com/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.admon.org/query-domain-name-whois-info-by-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generate random Chinese character in Python</title>
		<link>http://www.admon.org/generate-random-chinese-character-python/</link>
		<comments>http://www.admon.org/generate-random-chinese-character-python/#comments</comments>
		<pubDate>Sun, 05 Dec 2010 12:54:07 +0000</pubDate>
		<dc:creator>joseph</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[chinese]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[random]]></category>

		<guid isPermaLink="false">http://www.admon.org/?p=1003</guid>
		<description><![CDATA[This is a python script that can be used to generate random Chinese characters. Funny script! #!/usr/bin/python import random def rand_ch_ch(): head = random.randint(0xB0, 0xDF) body = random.randint(0xA, 0xF) tail = random.randint(0, 0xF) val = ( head]]></description>
			<content:encoded><![CDATA[<p>This is a python script that can be used to generate random Chinese characters. Funny script!</p>
<pre>
#!/usr/bin/python
import random
def rand_ch_ch():<span id="more-1003"></span>
    head = random.randint(0xB0, 0xDF)
    body = random.randint(0xA, 0xF)
    tail = random.randint(0, 0xF)
    val = ( head << 0x8 ) | (body << 0x4 ) | tail
    str = "%x" % val
    return str.decode('hex').decode('gb2312')
</pre>
<p>Not sure where it is originally from. If you're the creator, please let me know.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.admon.org/generate-random-chinese-character-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Query IP whois info in python</title>
		<link>http://www.admon.org/query-ip-whois-info-in-python/</link>
		<comments>http://www.admon.org/query-ip-whois-info-in-python/#comments</comments>
		<pubDate>Tue, 18 Jan 2005 05:38:41 +0000</pubDate>
		<dc:creator>joseph</dc:creator>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[whois]]></category>

		<guid isPermaLink="false">http://planet.admon.org/?p=528</guid>
		<description><![CDATA[This is a simple python script  based on some former rwhois code. It shows us an easy way on how to get detailed information about a specific IP address: joseph@e54:~$ python ip-whois.py 94.75.214.11 ====== whois.arin.net OrgName: RIPE Network Coordination Centre OrgID: RIPE Address: P.O. Box 10096 City: Amsterdam StateProv: PostalCode: 1001EB Country: NL ReferralServer: whois://whois.ripe.net:43 [...]]]></description>
			<content:encoded><![CDATA[<p>This is a simple python script  based on some former <a href="http://sourceforge.net/projects/rwhois/files/">rwhois</a> code. It shows us an easy way on how to get detailed information about a specific IP address:</p>
<pre>joseph@e54:~$ python <strong>ip-whois.py</strong> 94.75.214.11
====== whois.arin.net                        

OrgName:    RIPE Network Coordination Centre
OrgID:      RIPE
Address:    P.O. Box 10096<span id="more-528"></span>
City:       Amsterdam
StateProv:
PostalCode: 1001EB
Country:    NL

ReferralServer: whois://whois.ripe.net:43

NetRange:   94.0.0.0 - 94.255.255.255
CIDR:       94.0.0.0/8
NetName:    94-RIPE
NetHandle:  NET-94-0-0-0-1
Parent:
NetType:    Allocated to RIPE NCC
NameServer: NS-PRI.RIPE.NET
NameServer: SEC1.APNIC.NET
NameServer: SEC3.APNIC.NET
NameServer: TINNIE.ARIN.NET
NameServer: NS2.LACNIC.NET
Comment:    These addresses have been further assigned to users in
Comment:    the RIPE NCC region. Contact information can be found in
Comment:    the RIPE database at http://www.ripe.net/whois
RegDate:    2007-07-30
Updated:    2009-05-18</pre>
<p>The source code is listed below. You may copy the code into a text file and name it as <em>ip-query.py</em>:</p>
<pre>#!/usr/bin/env python
# Forwarded version from <a href="http://thomasfischer.biz/posts/ip-whois-query-via-python">thomasfischer.biz</a>!!!
#
import os, sys, string, time, getopt, socket, select, re, errno, copy, signal        

def queryWhois(query, server='whois.ripe.net'):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while 1:
        try:
            s.connect((server, 43))
        except socket.error, (ecode, reason):
            if ecode==errno.EINPROGRESS:
                continue
            elif ecode==errno.EALREADY:
                continue
            else:
                raise socket.error, (ecode, reason)
            pass
        break                                            

    ret = select.select ([s], [s], [], 30)

    if len(ret[1])== 0 and len(ret[0]) == 0:
        s.close()
        raise TimedOut, "on data"           

    s.setblocking(1)

    s.send("%sn" % query)
    page = ""
    while 1:
        data = s.recv(8196)
        if not data: break
        page = page + data
        pass

    s.close()

    if string.find(page, "IANA-BLK") != -1:
        raise 'no match'

    if string.find(page, "Not allocated by APNIC") != -1:
        raise 'no match'

    return page

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "usage: %s " % sys.argv[0]
        sys.exit(1)
    ip = sys.argv[1]

    for server in ['whois.arin.net', 'whois.ripe.net', 'whois.apnic.net', 'whois.lacnic.net', 'whois.afrinic.net']:
        try:
            res = queryWhois(ip, server)
            print '======', server
            print res
            break # we only need the info once
        except:
            pass</pre>
<p>If you wanna find whois information about some domain names, you might need to re-write these open-sourced scripts. An suggested alternative choice is <a href="http://code.google.com/p/pywhois/">pywhois which is hosted by code.google.com</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.admon.org/query-ip-whois-info-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

