Search results for 'socket'

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

linux socket source

2009. 8. 5. 17:22

쓸때마다 매번 찾는게 귀찮아서..

 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define SERVER "xxx.xxx.xxx.xxx"
#define PORT "xxxx"
#define TRUE 1

void error_handling(char *message);

int main(int argc, char **argv) {

    int i,sock;

    char exploit[]="";

    unsigned char recv[512]= {0, };

    int str_len;
    int option;
    socklen_t optlen;
    
    /************* socket initialize and connect ****************/    

    struct sockaddr_in serv_addr;
    sock=socket(PF_INET, SOCK_STREAM, 0);
    if(sock == -1)
        error_handling("socket() error");

    optlen = sizeof(option);
    option = TRUE;

    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
    memset(&serv_addr, 0, sizeof(serv_addr));

    serv_addr.sin_family=AF_INET;
    serv_addr.sin_addr.s_addr=inet_addr(SERVER);
    serv_addr.sin_port=htons(atoi(PORT));

    if(connect(sock, (struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
        error_handling("connect() error!");

    /****************** main start ********************/

    if((str_len = read(sock, recv, 64))==0)   //Read 1
        error_handling("read() error!");
    recv[str_len]=0;
    printf("Message from server : %s \n", recv); 

    if((str_len = read(sock, recv, 64))==0)   //Read 2
        error_handling("read() error!");
    recv[str_len]=0;
    printf("Message from server : %s \n", recv);

    if((str_len = write(sock, first, strlen(first))) == -1) ///write 1
       error_handling("write() error");
    
    if((str_len = read(sock, recv, 64))==0)  //Read 3
        error_handling("read() error!");
    recv[str_len]=0;
    printf("Message from server : %s \n", recv);  

    close(sock);
    return 0;
}

void error_handling(char *message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

'OS > Linux' 카테고리의 다른 글

redhat 9.0 networking problem in vmware  (0) 2010.06.20
about Signal  (0) 2009.12.09
Advanced Programming in the Unix Environment  (0) 2009.12.02
APUE 7장 연습문제  (0) 2009.11.27
codegate 2009. hamburger  (0) 2009.08.14
binary analysis in linux box without symbol  (0) 2009.06.15

badcob OS/Linux