googlecode :https://code.google.com/archive/p/python-proxy/source/default/source

# -*- coding: cp1252 -*-
# <PythonProxy.py>
#
#Copyright (c) <2009> <F醔io Domingues - fnds3000 in gmail.com>
#
#Permission is hereby granted, free of charge, to any person
#obtaining a copy of this software and associated documentation
#files (the "Software"), to deal in the Software without
#restriction, including without limitation the rights to use,
#copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the
#Software is furnished to do so, subject to the following
#conditions:
#
#The above copyright notice and this permission notice shall be
#included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
#OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
#HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
#WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
#OTHER DEALINGS IN THE SOFTWARE. """\
Copyright (c) <2009> <F醔io Domingues - fnds3000 in gmail.com> <MIT Licence> **************************************
*** Python Proxy - A Fast HTTP proxy ***
************************************** Neste momento este proxy ?um Elie Proxy. Suporta os m閠odos HTTP:
- OPTIONS;
- GET;
- HEAD;
- POST;
- PUT;
- DELETE;
- TRACE;
- CONENCT. Suporta:
- Conex鮡s dos cliente em IPv4 ou IPv6;
- Conex鮡s ao alvo em IPv4 e IPv6;
- Conex鮡s todo o tipo de transmiss鉶 de dados TCP (CONNECT tunneling),
p.e. liga珲es SSL, como ?o caso do HTTPS. A fazer:
- Verificar se o input vindo do cliente est?correcto;
- Enviar os devidos HTTP erros se n鉶, ou simplesmente quebrar a liga玢o;
- Criar um gestor de erros;
- Criar ficheiro log de erros;
- Colocar excep珲es nos s韙ios onde ?previs韛el a ocorr阯cia de erros,
p.e.sockets e ficheiros;
- Rever tudo e melhorar a estrutura do programar e colocar nomes adequados nas
vari醰eis e m閠odos;
- Comentar o programa decentemente;
- Doc Strings. Funcionalidades futuras:
- Adiconar a funcionalidade de proxy an髇imo e transparente;
- Suportar FTP?. (!) Aten玢o o que se segue s?tem efeito em conex鮡s n鉶 CONNECT, para estas o
proxy ?sempre Elite. Qual a diferen鏰 entre um proxy Elite, An髇imo e Transparente?
- Um proxy elite ?totalmente an髇imo, o servidor que o recebe n鉶 consegue ter
conhecimento da exist阯cia do proxy e n鉶 recebe o endere鏾 IP do cliente;
- Quando ?usado um proxy an髇imo o servidor sabe que o cliente est?a usar um
proxy mas n鉶 sabe o endere鏾 IP do cliente;
?enviado o cabe鏰lho HTTP "Proxy-agent".
- Um proxy transparente fornece ao servidor o IP do cliente e um informa玢o que
se est?a usar um proxy.
S鉶 enviados os cabe鏰lhos HTTP "Proxy-agent" e "HTTP_X_FORWARDED_FOR". """ import socket, thread, select __version__ = '0.1.0 Draft 1'
BUFLEN = 8192
VERSION = 'Python Proxy/'+__version__
HTTPVER = 'HTTP/1.1' class ConnectionHandler:
def __init__(self, connection, address, timeout):
self.client = connection
self.client_buffer = ''
self.timeout = timeout
self.method, self.path, self.protocol = self.get_base_header()
if self.method=='CONNECT':
self.method_CONNECT()
elif self.method in ('OPTIONS', 'GET', 'HEAD', 'POST', 'PUT',
'DELETE', 'TRACE'):
self.method_others()
self.client.close()
self.target.close() def get_base_header(self):
while 1:
self.client_buffer += self.client.recv(BUFLEN)
end = self.client_buffer.find('\n')
if end!=-1:
break
print '%s'%self.client_buffer[:end]#debug
data = (self.client_buffer[:end+1]).split()
self.client_buffer = self.client_buffer[end+1:]
return data def method_CONNECT(self):
self._connect_target(self.path)
self.client.send(HTTPVER+' 200 Connection established\n'+
'Proxy-agent: %s\n\n'%VERSION)
self.client_buffer = ''
self._read_write() def method_others(self):
self.path = self.path[7:]
i = self.path.find('/')
host = self.path[:i]
path = self.path[i:]
self._connect_target(host)
self.target.send('%s %s %s\n'%(self.method, path, self.protocol)+
self.client_buffer)
self.client_buffer = ''
self._read_write() def _connect_target(self, host):
i = host.find(':')
if i!=-1:
port = int(host[i+1:])
host = host[:i]
else:
port = 80
(soc_family, _, _, _, address) = socket.getaddrinfo(host, port)[0]
self.target = socket.socket(soc_family)
self.target.connect(address) def _read_write(self):
time_out_max = self.timeout/3
socs = [self.client, self.target]
count = 0
while 1:
count += 1
(recv, _, error) = select.select(socs, [], socs, 3)
if error:
break
if recv:
for in_ in recv:
data = in_.recv(BUFLEN)
if in_ is self.client:
out = self.target
else:
out = self.client
if data:
out.send(data)
count = 0
if count == time_out_max:
break def start_server(host='', port=8080, IPv6=False, timeout=60,
handler=ConnectionHandler):
if IPv6==True:
soc_type=socket.AF_INET6
else:
soc_type=socket.AF_INET
soc = socket.socket(soc_type)
soc.bind((host, port))
print "Serving on %s:%d."%(host, port)#debug
soc.listen(0)
while 1:
thread.start_new_thread(handler, soc.accept()+(timeout,)) if __name__ == '__main__':
start_server()

python http代理代码的更多相关文章

  1. python 常忘代码查询 和autohotkey补括号脚本和一些笔记和面试常见问题

    笔试一些注意点: --,23点43 今天做的京东笔试题目: 编程题目一定要先写变量取None的情况.今天就是因为没有写这个边界条件所以程序一直不对.以后要注意!!!!!!!!!!!!!!!!!!!!! ...

  2. python调用Java代码,完毕JBPM工作流application

    1.缘由 有一庞大Python django webproject,要引入工作流引擎,像OA一样.方便的流程控制与管理.Python或django关于工作流的开源插件,稀少,并且弱爆了,终于选用jav ...

  3. python使用代理ip

    python使用代理的方法有两种 1. #先创建代理ip对象 proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137: ...

  4. python通过代理刷网页点击量

    python通过代理刷网页点击量 更新异常处理情况 @time 2013-0803 更新循环里计数问题和随机等待时间问题 #!/usr/bin/python #-*- coding:utf-8 -*- ...

  5. Python 坑爹之 代码缩进

    建议:统一使用空格!!!!!!!!!不要Tab Python代码缩进   这两天python-cn邮件列表有一条thread发展的特别长,题目是<python的代码缩进真是坑爹>(地址), ...

  6. Python第一行代码

    Python版本:Python 3.6.1 0x01 命令行交互 在交互式环境的提示符>>>下,直接输入代码,按回车,就可以立刻得到代码执行结果.现在,试试输入100+200,看看计 ...

  7. python的PEP8 代码风格指南

    PEP8 代码风格指南 这篇文章原文实际上来自于这里:https://www.python.org/dev/peps/pep-0008/ 知识点 代码排版 字符串引号 表达式和语句中的空格 注释 版本 ...

  8. 用python处理html代码的转义与还原

    用python处理html代码的转义与还原   转义 escape: import cgi s = cgi.escape("""& < >" ...

  9. 【转】利用Boost.Python将C++代码封装为Python模块

    用Boost.Python将C++代码封装为Python模块 一.     基础篇 借助Boost.Python库可以将C/C++代码方便.快捷地移植到python模块当中,实现对python模块的扩 ...

随机推荐

  1. IIS发布网站

    IIS发布网站几个问题 1.部署步骤:http://jingyan.baidu.com/article/3065b3b6e5becdbecff8a4d5.html Win7下IIS报503Servic ...

  2. lua自定义迭代器

    迭代器 http://www.tutorialspoint.com/lua/lua_iterators.htm 迭代器能够让你遍历某个集合或者容器中的每一个元素. 对于lua来说, 集合通常指代 ta ...

  3. Redis在Linux下的安装和启动和配置

    第一步:下载Redis安装包,下载版本:3.0.5 在所在目录右键打开终端输入命令: wget http://download.redis.io/releases/redis-3.0.5.tar.gz ...

  4. DNS压力测试工具dnsperf简介

    dnsperf是我最近写的一个开源的DNS压力测试工具,用户可以用它来对DNS服务器或者Local DNS做压力测试.dnsperf目前的实现是单进程模式,通过epoll非阻塞地处理网络事件. dns ...

  5. 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...

  6. 【皇甫】☀ 图_substring

    substring是啥?

  7. 【004: gcc 和 clang 的简单比较】

  8. virtualenv 安装 lxml

    sudo apt-get install zlib1g-dev sudo apt-get install lib32z1-dev sudo apt-get install libxml2-dev li ...

  9. MS CRM 2013 Plugin 注册工具登录后空白

    解决办法 把en-us, zh-CN 目录随便改个名字就好了

  10. [已解决] 快速理解RSA算法

    RSA算法基础详解 http://www.cnblogs.com/hykun/p/RSA.html RSA算法原理(一) http://www.ruanyifeng.com/blog/2013/06/ ...