Python implements a simple HTTP proxy

Source: Internet
Author: User

There is a openwrt router, 16M Flash storage + 64M memory, can be installed Python. Because there is no URL to the site access records, want to write one.


HTTP 1.1 is a TCP connection with header and body

Using Python Listen 8000 port

Setting up the browser, using localhost 8000 http proxy mode

SOURCE py2.7:

1 #Coding:utf-82 ImportSocket3 ImportSYS4 ImportRe5 ImportOS6 Import Time7 8Host =''9Port = 8000Ten  One #creating a Socket object AProxy_sock =Socket.socket (Socket.af_inet,socket. SOCK_STREAM) - Try: - Proxy_sock.bind ((host,port)) the except: -Sys.exit ("python proxy bind error") -  - Print "python proxy Open" +  -Proxy_sock.listen (1024) +  whileTrue: ACONN,ADDR =proxy_sock.accept () at os.fork () -     Print "Client Connent:{0}:{1}". Format (addr[0], addr[1]) -  -     #Receive Data -Client_data = CONN.RECV (1024) -  in     #analysis to get header information -Header = Client_data.split ("\ r \ n") toHost = Header[1].split (":") [1].strip () +url = header[0].split (" ") [1].strip () -  the     #Statistical Access Records *     PrintTime.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (Time.time ())) $     PrintHostPanax Notoginseng     PrintURL -  the     #Establish a connection +Http_sock =Socket.socket (Socket.af_inet,socket. SOCK_STREAM) AHttp_sock.connect (Host, 80)) the Http_sock.sendall (client_data) +      while(True): -Http_data = HTTP_SOCK.RECV (1024) $         ifHttp_data: $ conn.send (http_data) -         Else: -              Break the http_sock.close () - Wuyi #Close all Connections the proxy_sock.close () - Print "python proxy close"

From the header can be extracted to, access to the URL, cookies and other information, theoretically non-HTTPS can also be extracted to post information.

The disadvantage is that the performance is not good and does not implement Connection: keep-alive

Because the use of Fork () win should not be used.

It seems that it is better to add in the network card driver.

Python implements a simple HTTP proxy

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.