Search results for 'Python'

handling HTTP by python module

2011. 7. 4. 01:03

파이썬으로 네크워크 프로그래밍을 할때 일반적으로 아래의 모듈들을 사용한다.

socket, httplib,urllib, urllib2, etc..

상황에 따라 다르겠지만 urllib, urllib2, httplib 애들은 이름부터 비슷해서 기능들도 비슷비슷하다

각각 사용해야 될 상황이 있을 법한데 그때 그때 구현해서 쓰다보니 뭐가 뭔지 헷갈림.. 
그래서 구글링을 해보니 생각보다 간단하다.

1) urllib2는 Request class를 통해서 헤더를 조작할수 있다는 것과
2) urlencode는 urllib에만 있다는 것

그러니깐 urllib2는 보다 디테일한 제어가 가능하지만 몇몇 기능 떄문에 urllib를 써야 한다는 정도.
httplib는 아래 코멘트로 설명이 될듯.

If you're dealing solely with http/https and need access to HTTP specific stuff, use httplib. For all other cases, use urllib2.
urllib/urllib2 is built on top of httplib. It offers more features than writing to httplib directly.


example. socket 

from socket import *

host = "blabla"
port = 80
payload = "GET / HTTP/1.1\r\n"

s = socket(AF_INET, SOCK_STREAM)
s.connect((host, port))
s.send(payload)
r = s.recv(1024)
print "[+] Receive - %s" % r


example urllib2,urllib
wechall.net에 있는 문제 중에 하나.
urllib2에서 Request 클래스를 생성할 때, data 값이 있으면 POST 로 전송한다. 
따라서 GET으로 전송하고 싶으면 add_header 메소드로 추가.


import urllib,urllib2,re

url = 'http://www.wechall.net/challenge/training/programming1/index.php?action=request'
callback_url = 'http://www.wechall.net/challenge/training/programming1/index.php?answer='

#param = {'action':'request'}
#data = urllib.urlencode(param)

sid = "WC4_SID=921244-6205-R8w9DSKbppv6P4pE"

req = urllib2.Request(url)
req.add_header('cookie',sid)
f = urllib2.urlopen(req)

text = f.read()
#answer = re.findall('page_wrap\">\n[a-zA-Z0-0]{9}',text)
t = re.findall('[a-zA-Z0-9]+',text)
t.reverse()
answer = t[0]

req = urllib2.Request(callback_url+answer)
req.add_header('cookie',sid)
f = urllib2.urlopen(req)
print f.read()

'Code > Python' 카테고리의 다른 글

SendMessage by winappdbg  (0) 2013.06.12
decode captcha by python  (0) 2012.11.12
ISEC 2009 level3 solution by winappdbg  (0) 2010.09.16
hust 8th level D - python  (0) 2009.10.17

badcob Code/Python

hust 8th level D - python

2009. 10. 17. 19:07

받아온 키를 한줄 씩 전송 해 봤지만 첫 줄만 보내도 패스워드를 얻을 수 있었다.


import struct,base64,httplib, urllib
from socket import *
svrsocket = socket(AF_INET, SOCK_STREAM)
svrsocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
svrsocket.bind(('', 7777))
svrsocket.listen(1)
conn, addr = svrsocket.accept()
i = 0 
sum = ''
buf =conn.recv(1024)
#print buf
j = 0 
result = []
try:
    while 1:
        if buf[j]:
            if buf[j] == '\x0a':
                j+=1
                result.append(sum)
                sum = ''
                pass
            sum += buf[j]
            j+=1
        else:
            break
except:
    pass
#print result
conn.close()

try:
    for x in result:
        auth = base64.b64encode("admin:21d0ac6b17066785986d4ea3dcaf2c72")
        params = urllib.urlencode({'passwd':x,'submit':'SEND+PASSWORD+KEY'})
        headers = {'Content-Type':'application/x-www-form-urlencoded','Authorization': 'Basic %s'%auth}
        conn = httplib.HTTPConnection("220.95.152.132:80")
        conn.request("POST", "/login_ok.php", params, headers)
        response = conn.getresponse()
        data = response.read()
        print data
        conn.close()
except:
    pass

'Code > Python' 카테고리의 다른 글

SendMessage by winappdbg  (0) 2013.06.12
decode captcha by python  (0) 2012.11.12
handling HTTP by python module  (0) 2011.07.04
ISEC 2009 level3 solution by winappdbg  (0) 2010.09.16

badcob Code/Python

python challenge level5

2009. 8. 27. 00:20

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

pronounce it 이라고 적혀진 페이지가 있다.

소스를 보면 아래의 내용을 볼 수 있다.

<peakhell src="banner.p"/>
<!-- peak hell sounds familiar ? -->

banner.p
파일을 다운받아서 보았지만 별다른 힌트는 없어보였다
peakhell 이 도대체 뭘까.. 이리저리 고민하다가 forum의 hint 페이지를 찾아보았다.
(http://www.pythonchallenge.com/forums/)

힌트 없냐는 말에 누군가가 "Try browsing "Global Modules Index" 라는 코멘트를 달아놓았다.

Global Module 중에 peakhell과 비슷한 발음이 나는 녀석을 찾다보니 PICKLE 이라는 녀석이 있었다.

PICKLE 에 대한 설명은 http://docs.python.org/library/pickle.html 에서 볼 수 있다.
간략히 말하면 pickle module은 python object serialization 으로 파이썬 객체를  바이트 스트림으로 바꿀 수 있다. (unplckling 이라 하면 이 반대의 과정을 의미한다)

이점에 착안해서 banner.p를 읽어와서 이를 unpickling 해보았다.


import pickle

f = open("banner.p",'rb')
result = pickle.load(f)
list_length = len(result)
i=0
temp = ()
while i < list_length:
	tuple_length  = len(result[i])
	j = 0
	word = ''
	while j < tuple_length: 
		temp = result[i][j]
		j+=1
		k = 0
		while k < temp[1]:
			if temp[0] ==' ':
				word += ' ' 				
			else:
				word += temp[0]
			k+=1
	print word
	i+=1


코드를 수행하면 banner command를 실행한 것처럼 channel 이라고 크게 찍히는 문자열을 볼 수 있다.

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

'War game > pythonchallenge' 카테고리의 다른 글

pythonchallenge level11  (0) 2009.10.22
pythonchallenge level10  (0) 2009.10.20
pythonchallenge level9  (0) 2009.10.16
pythonchallenge level8  (0) 2009.10.16
pythonchallenge level7  (0) 2009.10.16
python challenge level6  (0) 2009.09.21
pythonchallenge level4  (0) 2009.08.20
pythonchallenge level3  (0) 2009.08.19
pythonchallenge level2  (0) 2009.08.17
pythonchallenge level1  (0) 2009.08.17

badcob War game/pythonchallenge

pythonchallenge level4

2009. 8. 20. 02:01

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

소스 보기를 하면 level4의 힌트가 적혀있다

urllib may help. DON'T TRY ALL NOTHINGS, since it will never end.
400 times is more than enough.


화면에 있는 그림을 클릭했더니 get 메소드로 nothing 이라는 값에12345를 넘겨주며 (<a href="linkedlist.php?nothing=12345">) nothing의 다음 값을 알려준다.

and the next nothing is 92512

이처럼 페이지에 나온 문자열을 정규표현식으로 파싱해서 nothing에 집어넣은후 계속 쿼리를 날려보았다.
중간 중간에 나오는 트릭에 대한 처리를 하면서  peak.html 이라고 나오는 것을 확인하였다.

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


import urllib
import re

def get_page(number):
	while 1:
		i = 0
	 	url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s" % number
	 	f = urllib.urlopen(url)
		print url
		file = f.read()
		print file
		text = re.findall("next nothing is \d+",file)
		if text:
			text_last = text[0]
			number_list = re.findall("[0-9]+",text_last)
			number = ''
			while 1:
				number += number_list[i]
				i +=1
				if i == len(number_list): break
		else:
			text = re.findall("Yes", file)
			if text:
				number = 92118/2
			else:
				break
				
num = 12345
get_page(num) 




'War game > pythonchallenge' 카테고리의 다른 글

pythonchallenge level11  (0) 2009.10.22
pythonchallenge level10  (0) 2009.10.20
pythonchallenge level9  (0) 2009.10.16
pythonchallenge level8  (0) 2009.10.16
pythonchallenge level7  (0) 2009.10.16
python challenge level6  (0) 2009.09.21
python challenge level5  (0) 2009.08.27
pythonchallenge level3  (0) 2009.08.19
pythonchallenge level2  (0) 2009.08.17
pythonchallenge level1  (0) 2009.08.17

badcob War game/pythonchallenge

pythonchallenge level2

2009. 8. 17. 20:34

level 2 : http://www.pythonchallenge.com/pc/def/ocr.html
--------------------------------------------------------------------------
Hint :
recognize the characters. maybe they are in the book,
but MAYBE they are in the page source.

--------------------------------------------------------------------------
웹페이지의 소스를 보니  특수문자들로 보이는 엄청 긴 문자열이 있고

<!--
find rare characters in the mess below:
-->

라는 주석을 볼 수 있다.

특수 문자들 사이에 있는 알파릭 문자들을 뽑아내 보았다.


str = """%%$@_$^__#)^....."""

answer = ''i=0
while 1:
 if ord(str[i]) > 96 and ord(str[i]) < 123: answer += str[i]
 i+=1
 if i == len(str): break
print answer 


숨어있는 문자들은 equality

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

'War game > pythonchallenge' 카테고리의 다른 글

pythonchallenge level11  (0) 2009.10.22
pythonchallenge level10  (0) 2009.10.20
pythonchallenge level9  (0) 2009.10.16
pythonchallenge level8  (0) 2009.10.16
pythonchallenge level7  (0) 2009.10.16
python challenge level6  (0) 2009.09.21
python challenge level5  (0) 2009.08.27
pythonchallenge level4  (0) 2009.08.20
pythonchallenge level3  (0) 2009.08.19
pythonchallenge level1  (0) 2009.08.17

badcob War game/pythonchallenge

pythonchallenge level1

2009. 8. 17. 18:26

사이트 url은 이곳이며 level1은 여기를 클릭.

everybody thinks twice before solving this.

g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.

위와 같은 글귀와

K -> M
O -> Q
E -> G

라고 적혀진 노트를 볼 수 있다. 아스키 코드를 2씩 증가시키므로 

......
    word += chr(ord(txt[i])+ 2)
  i+=1
  if i == length : break
 return word

이런식으로 만들어서 디코딩을 해봤더니 아래와 같은 문장을 볼 수 있었다.
-----------------------------------------------------------------------------------------------
i hope you didnt translate it by hand. thats what computers are for. doing it in
 by hand is inefficient and that's why this text is so long. using string.maketr
ans() is recommended. now apply on the url
------------------------------------------------------------------------------------------------
그냥 끝내기가 멋적어서 string.maketrans를 써서 다시 만든 코드.


import string

def decode_str(txt):
 word = ''
 firstchar = string.uppercase + string.lowercase
 secondchar = '{'+'}'
 move_str1 = string.maketrans(firstchar, "CDEFGHIJKLMNOPQRSTUVWXYZ[\cdefghijklmnopqrstuvwxyz{}") 
 move_str2 = string.maketrans(secondchar,"ab")
 word = txt.translate(move_str1) 
 return word.translate(move_str2)

str = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj"
#str = "http://www.pythonchallenge.com/pc/def/map.html"

answer = ''
answer = decode_str(str)
print answer


힌트를 따라서 url에 적용한뒤 주소창에 입력. (map.html)
http://www.pythonchallenge.com/pc/def/ocr.jvon

Have you ever heard of jvon files !?

jvon 확장자라..들어본적 없다. 구글링을 해봐도 나오지 않았다;
혹시나해서 ocr.html로 입력했더니 level2 페이지를 볼 수 있었다.
http://www.pythonchallenge.com/pc/def/ocr.html

'War game > pythonchallenge' 카테고리의 다른 글

pythonchallenge level11  (0) 2009.10.22
pythonchallenge level10  (0) 2009.10.20
pythonchallenge level9  (0) 2009.10.16
pythonchallenge level8  (0) 2009.10.16
pythonchallenge level7  (0) 2009.10.16
python challenge level6  (0) 2009.09.21
python challenge level5  (0) 2009.08.27
pythonchallenge level4  (0) 2009.08.20
pythonchallenge level3  (0) 2009.08.19
pythonchallenge level2  (0) 2009.08.17

badcob War game/pythonchallenge