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