Google
 
loading...

Linux:

libc6's prctl function with option PR_SET_NAME
       PR_SET_NAME (since Linux 2.6.9)
              Set the process name for the calling process, using the value in
              the location pointed to by (char *) arg2.  The name can be up to
              16  bytes  long,  and  should  be null terminated if it contains
              fewer bytes.

code is

import ctypes
libc = ctypes.CDLL('libc.so.6')
libc.prctl(15, '%s\0' %procname, 0, 0, 0)

---------------------------------------------------------------------------------------

BSD:

import dl
libc = dl.open('/lib/libc.so.6')
libc.call('setproctitle', '%s\0' %procname)

---------------------------------------------------------------------------------------
a script to show value of MACRO

echo -e "#include <sys/prctl.h>\n#include <stdio.h>\nint main(){printf(\"%d\\\n\",PR_SET_NAME);return 0;}" |gcc -xc - -o /tmp/test && /tmp/test



Tags: python |

I posted an article about WOL over Internet, it referred a python script which send UDP WOL Magic-package over UDP. Recent the script has been updated, the reason is my office firewall block any UDP package except for DNS query, even when an non-DNS UDP package was tried to send through port 53, the firewall block it.

what I need to do is encapsulate a Magic-package into a fake DNS query, indeed my strategy is pack it into query domain name part. The package head is easy to construct. So the problem is how to pack the 102(6+6*16) bytes Magic-package.

----------------------------------------------------------------------------------------

If you can't understand the paragraph below, it's my fault, I can't explain it well. So don't read it again, goto code, everything is in code, and the python code is easy to understand.

----------------------------------------------------------------------------------------

The max length of a label in domain name is 63, which can contain first 6 '0xff' and 8 mac, (here 6+6*8=54 bytes is done). Then the first byte of remaining 48(102-54) bytes (also the first byte of 9th mac) is the length of the second label of domain name, so this byte value must between 1 and 63. if it's in this range(let's say it's 10), the next 10 bytes is the second label in domain name, (here 6+6*8+1+10=65 bytes is done), and the first byte value of remain 37 bytes must between 1 and 63 ..., etc. We can call "the first byte of remaining bytes" "key bytes". Let's repeat this process until all 102 bytes are consumed, if all key bytes are between 1 and 63, we can pack the Magic-package into a domain name part. If we got a key bytes which is not in the range before consuming all 102 bytes, we fails.

Notice, we can start from not only the first byte of remaining 48 bytes in first iteration of process, actually we can regard any byte of the 9th mac as the length of the second label, bytes before that key byte can be pack into first label, that's is the first label has length of 54+(number of byte in 9th mac before key byte). So we have 6 chance.

----------------------------------------------------------------------------------------



Tags: python | wol |

Added an issue.

And tinyMCE dose not work now in this Edit post page, why? my problem or tinyMCE's?

gae has changed a lot since last study last September, there are 5 item in "main" group in the gae admin page, but 2 of them (Cron jobs and Task Queues) never used. Beside this, the memcache api, XMPP api is the same status. It seems that a new study of gae is necessary.

in Hitachi, Ibaraki, Japan 2009/09/05

 

 


View Larger Map



Tags: python | gae | glog |

You need a file which has only one copy on your home PC's harddisk, but you are in office or another city even another country! What would you do? Call your neighbor to ask him break into your house and power on your PC, then you can fetch file by sftp?

Here is the solution to avoid breaking your door. Remote Power On

Thanks for WOL tech and Python, It's so easy!

What We need:

1. A WOL(wake on lan) supported NIC

    My Asus K8N integrated NIC

2. A tool to send Magic Package

    A Python script no more than 40 lines

3. An ADLS router supporting DDNS, ARP binding and NAT port mapping

    TP-Link WR541G/542G

 

Here is steps:

1. Enable WOL in BIOS settings.

    There are a bunch of guides on google, find one for your motherboard and network card. Notice: ACPI 2.0 must be enabled, I wasted hours before success on this misconfig.

2. save script below as wol.py

#!/usr/bin/python
import sys
import struct
from socket import *


def usage():
    print """send UDP packet to broadcasting address to remote wakeup
UDP package format is FFFFFFFFFFFF0017314BACCB....................
                      (fixed 6 FF)(   mac    )(repeat mac 15 times)

usage: wol.py broadcasting_address udp_port target_host_mac

example: wol.py sevenever.vicp.net 4672 0017314BACCB
"""

def main():
    if len(sys.argv) != 4:
        usage()
        return 1
    bc_addr = sys.argv[1]
    udp_port = int(sys.argv[2])
    mac = sys.argv[3]
    hw_addr = struct.pack('BBBBBB', int(mac[0:2], 16),
                                    int(mac[2:4], 16),
                                    int(mac[4:6], 16),
                                    int(mac[6:8], 16),
                                    int(mac[8:10], 16),
                                    int(mac[10:12], 16))
   
    msg = '\xff' * 6 + hw_addr * 16
   
    sk = socket(AF_INET, SOCK_DGRAM)
    sk.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
   
    sk.sendto(msg, (bc_addr, udp_port))
    sk.close()
   
if __name__ == '__main__':
    sys.exit(main())

3. Setting on your router

    3.1 add an arp binding record

        [your PC IP address] ---- [your netcard MAC address]

        say:[192.168.1.7] ---- [00-11-D8-93-E9-08]

    3.2 add a NAT port mapping

        since the tool above send UDP package to your router, your router must know how to forward package to your PC, So

add a port mapping:

        Protocol: UDP

        Service Port: any (say 4672)

        LAN Host IP: The IP binded in step 3.1

        *may be you have had an UDP port mapping for edonkey or some application else, if so you can just reuse that setting and do nothing for this step 3.2.

    3.3 setup DDNS on router

        The last thing is you must know your router's Internet Address, if your ISP assign you a fixed pulic IP(lucky guy! that's impossible for China where I living), you just remember it, or you need setup DDNS( like oray.net or 3322.org ). Google it, you will find lots of guides. Here I asume you can access your router by name: somename.3322.org.

Now we have done all settings, The command for power on our home PC remotely in office or anywhere is:

./wol.py somename.3322.org 4672 0011D893E908

Enjoy!

 

 

 



Tags: python | WOL | DDNS |

urrent(2009-03-22) flashgot does not fake the User-Agent HTTP header as Firefox if downloading using wget, I dont know how other download manager is. This is not a big problem if you does not download videos(like flv) from a video site which deny wget according the User-Agent HTTP header.

But I found almost all video sites check this header for proventing thief, so the video detecter of flashgot become not so useful.

Actually, wget do have parameter "-U,  --user-agent=AGENT" to fake the HTTP header, so the solution is here:

This python script is a proxy when flashgot call wget to download, it add user-agent "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.0.7) Gecko/2009030422 Ubuntu/8.10 (intrepid) Firefox/3.0.7 GTB5"(my firefox version) when invoke wget.

To use it,

1.save it as "dflv" to some directory like ~/bin

2.config flashgot, add a new download manager, name it "dflv", the executable path should be the file path you saved in [1], and arguments template *must* be "[FOLDER] [REFERER] [CFILE] [UFILE]"(with out the quote mark)

OK, now you can doanload vide by short-cut key Ctrl+F7

notice:

only OS with python and wget and xterm supported, I think most Linux and freebsd have them. Windows which installed python and wget should be supported, I'll give a try later cause no Windows at hand.

File:

-------------------------------------------------------------------------------

#!/usr/bin/python

import os
import sys
from datetime import datetime

log = False

logdir = os.path.expanduser("~/.dflv")
dfname = datetime.now().isoformat()

log and os.makedirs(os.path.sep.join([logdir,dfname]))
logfile = os.path.sep.join([logdir,dfname,'log'])
wgetlogfile = os.path.sep.join([logdir,dfname,'wgetlog'])

log = log and open(logfile,'w')

try:
    ua = "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.0.7) Gecko/2009030422 Ubuntu/8.10 (intrepid) Firefox/3.0.7 GTB5"

    log and log.write(' '.join(sys.argv))
   
    _, folder, referer, cookiefile, urlfile = sys.argv

    cmd = '''xterm -e 'wget -c -P "%s" --content-disposition -U "%s" --referer="%s" --load-cookies="%s" -i "%s";read -n 1 -s' ''' % (folder, ua, referer, cookiefile, urlfile)

    log and log.write(cmd + '\n')

    os.system(cmd)
except Exception,e:
    log and log.write(str(e) + '\n')



Tags: python | flashgot |

level15:

pretty easy, 1\d{1,2}6 year jananry 26th is a Monday.

whom? use wikipedia

http://www.pythonchallenge.com/pc/return/mozart.html


level16:

shift each line to make the purple bars as one stick?

five 195

http://www.pythonchallenge.com/pc/return/romance.html


level17:

in level4, a cookie is set:

info=you+should+have+followed+busynothing...

start chain with busynothing=12345 and collect all cookies

BZh hint decompressing

'is it the 26th already? call his father and inform him that "the flowers are on their way". he\'ll understand.'

mozart's father is Leopold, use phonebook.phone('Leopold') in level13 I got

http://www.pythonchallenge.com/pc/return/violin.html

request http://www.pythonchallenge.com/pc/stuff/violin.php with cookie "info=the%20flowers%20are%20on%20their%20way"

oh well, don't you dare to forget the balloons.

http://www.pythonchallenge.com/pc/return/balloons.html


level18:

the difference is brightness.html

difflib.ndiff() lines in delta.txt, and write to each of '-', '+', ' ' to file. they are png image.

http://butter:fly@www.pythonchallenge.com/pc/hex/bin.html


level19:

computer is out of order, byteorder is reversed. So byteswap bytes in indian.wav's frames.

http://www.pythonchallenge.com/pc/hex/idiot.html

http://www.pythonchallenge.com/pc/hex/idiot2.html


level20:

Content-Range is:  bytes 0-30202/2123456789

add request header "range bytes=30202-30202", got:

---------------------------------------------------------------

Why don't you respect my privacy?
we can go on in this way for really long time.
stop this!
invader! invader!
ok, invader. you are inside now.
---------------------------------------------------------------

from back to front, add request header "range bytes=2123456789-2123456789", got:

esrever ni emankcin wen ruoy si drowssap eht

the password is your new nickname in reverse.

and it is hiding at 1152983631.

at 1152983631: got a zip file encrypted

the password is redavni

we are in level 21


level21:

file starts with 78 9c is zlib compressed file.

repeating decompress it with zlib or bz2 until get error, see the tail of decompressing result, it's 9c 78

"look at your logs"

log our action, mark zlib decompressing as "x", bz2 decompressing as "B", mark reverse as "\n"

http://www.pythonchallenge.com/pc/hex/copper.html



level8:

the un and pw startswith 'BZh', which is magic number of a bz2 file, so you use bz2 module:

bz2.decompress

http://www.pythonchallenge.com/pc/return/good.html


level9:

first and second is coordinations of pots.

use ImageDraw.polygon([first],fill=color)

I first tried gnu, then cow, at last bull

http://www.pythonchallenge.com/pc/return/bull.html


level10:

len(a[30]) = ?

a = [1, 11, 21, 1211, 111221, 

the next item is the description of previous item
11 is one 1
21 is two 1
1211 is one two, one one
111221 is one one, one two, two one

http://www.pythonchallenge.com/pc/return/5808.html

level11:

http://bg5hfc.spaces.live.com/blog/cns!E67CCF4FFB0BE86!1147.entry

I still have no idea how they get the way.

http://www.pythonchallenge.com/pc/return/evil.html


level12:

evil2.jpg-->evil2.gfx

dispatch this file to five file, you'll get the word by "file" them.

http://www.pythonchallenge.com/pc/return/disproportional.html


level13:

xml-rpc phonebook.php listMethods

555-ITALY

try -- 555-48259 55548259 ITALY italy

http://www.pythonchallenge.com/pc/return/italy.html


level14:

wire.png is a 10000*1 image, convert to 100*100?

consider

remember: 100*100 = (100+99+99+98) + (...

and title of this level "walk around"

source below:

import Image

def turn():
global fl,fi,f
fi=(fi+1)%4
f=fl[fi]

src = Image.open('wire.png')
des = Image.new('RGB', (100,100))

# direction functions
r = lambda (x,y):(x+1,y)
d = lambda (x,y):(x,y+1)
l = lambda (x,y):(x-1,y)
u = lambda (x,y):(x,y-1)

# direction functions list
fl = [r,d,l,u]

# current direction function index
fi = 0

# current direction function
f=r

# current postion
pos = (-1,0)

index = -1
for i in range(100):
index += 1
pos = f(pos)
des.putpixel(pos,src.getpixel((index,0)))


for i in range(99,0,-1):
for m in range(2):
turn()
for k in range(i):
index += 1
pos = f(pos)
des.putpixel(pos,src.getpixel((index,0)))

des.save('cat.png')

http://www.pythonchallenge.com/pc/return/cat.html

 

 

 



 

Hi, I start to play www.pythonchallenge.com, I'll post answers here and source at my source repository.


level0:

2**38

http://www.pythonchallenge.com/pc/def/274877906944.html


level1:

string.translate('map',''.join(chr((i+2)%256) for i in range(256)))

http://www.pythonchallenge.com/pc/def/ocr.html


level2:

get the rare letters and rearrange to a word

http://www.pythonchallenge.com/pc/def/equality.html


level3:

[k[4] for k in re.findall('[a-z][A-Z]{3}[a-z][A-Z]{3}[a-z]',s,re.M)]

http://www.pythonchallenge.com/pc/def/linkedlist.html


level4:

12345

50010

53522

92118

46059

http://www.pythonchallenge.com/pc/def/peak.html


level5:

pickle banner.p

and print them

http://www.pythonchallenge.com/pc/def/channel.html


level6:

http://www.pythonchallenge.com/pc/def/channel.zip

zipfile.ZipFile.infolist comment

http://www.pythonchallenge.com/pc/def/hockey.html

http://www.pythonchallenge.com/pc/def/oxygen.html


level7:

use PIL to pick pixel from that image.

coordinate is (i*7, 42)

got RGB and chr() to:

smart guy, you made it. the next level is [105, 110, 116, 101, 103, 114, 105, 116, 121]

chr() again

http://www.pythonchallenge.com/pc/def/integrity.html


 

 



print re.sub(r'(\\x([\da-f]+)?)',lambda x:chr(int(x.group(2),16)),r'\xd6\xd0\xb9\xfa')



Tags: python | re |

gae 中
如果是html page的GET和POST数据,self.request.get['name']获得的是unicode类型
如果是XHR(xmlhttprequest)的GET和POST数据,self.request.get['name']获得的是str类型(utf-8)

python 中调用父类同名方法的方法fromlimodou
    class TestBase(object):
        def myMethod(self):
            pass

    class MyTest1(TestBase):
        def myMethod(self):
            super(MyTest1, self).myMethod()
            #other process



Tags: python | gae | glog |