python http代理代码
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代理代码的更多相关文章
- python 常忘代码查询 和autohotkey补括号脚本和一些笔记和面试常见问题
笔试一些注意点: --,23点43 今天做的京东笔试题目: 编程题目一定要先写变量取None的情况.今天就是因为没有写这个边界条件所以程序一直不对.以后要注意!!!!!!!!!!!!!!!!!!!!! ...
- python调用Java代码,完毕JBPM工作流application
1.缘由 有一庞大Python django webproject,要引入工作流引擎,像OA一样.方便的流程控制与管理.Python或django关于工作流的开源插件,稀少,并且弱爆了,终于选用jav ...
- python使用代理ip
python使用代理的方法有两种 1. #先创建代理ip对象 proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137: ...
- python通过代理刷网页点击量
python通过代理刷网页点击量 更新异常处理情况 @time 2013-0803 更新循环里计数问题和随机等待时间问题 #!/usr/bin/python #-*- coding:utf-8 -*- ...
- Python 坑爹之 代码缩进
建议:统一使用空格!!!!!!!!!不要Tab Python代码缩进 这两天python-cn邮件列表有一条thread发展的特别长,题目是<python的代码缩进真是坑爹>(地址), ...
- Python第一行代码
Python版本:Python 3.6.1 0x01 命令行交互 在交互式环境的提示符>>>下,直接输入代码,按回车,就可以立刻得到代码执行结果.现在,试试输入100+200,看看计 ...
- python的PEP8 代码风格指南
PEP8 代码风格指南 这篇文章原文实际上来自于这里:https://www.python.org/dev/peps/pep-0008/ 知识点 代码排版 字符串引号 表达式和语句中的空格 注释 版本 ...
- 用python处理html代码的转义与还原
用python处理html代码的转义与还原 转义 escape: import cgi s = cgi.escape("""& < >" ...
- 【转】利用Boost.Python将C++代码封装为Python模块
用Boost.Python将C++代码封装为Python模块 一. 基础篇 借助Boost.Python库可以将C/C++代码方便.快捷地移植到python模块当中,实现对python模块的扩 ...
随机推荐
- Javascript模板引擎:Hogan
hogan.js是一个开源前端模板引擎,无逻辑的设计,简单好用,性能也不错. 使用 引入hogan.js,下载链接:http://www.bootcdn.cn/hogan.js/,然后通过hogan. ...
- Hive:org.apache.hadoop.hdfs.protocol.NSQuotaExceededException: The NameSpace quota (directories and files) of directory /mydir is exceeded: quota=100000 file count=100001
集群中遇到了文件个数超出限制的错误: 0)昨天晚上spark 任务突然抛出了异常:org.apache.hadoop.hdfs.protocol.NSQuotaExceededException: T ...
- GetLastError()函数返回值及含义
GetLastError返回的值通过在api函数中调用SetLastError或SetLastErrorEx设置.函数并无必要设置上一次错误信息,所以即使一次GetLastError调用返回的是零值, ...
- 写了placement new就要写placement delete
"placement new"通常是专指指定了位置的new(std::size_t size, void *mem),用于vector申请capacity剩余的可用内存. 但广义的 ...
- SetSysColors 修改系统颜色
首先我们来看一下SetSysColors函数的原型: BOOL WINAPI SetSysColors( __in int cElements, //要改变的对象的数量 __in const INT* ...
- Uml学习-用例建模简介
用例建模简介 用例建模是UML建模的一部分,它也是UML里最基础的部分.用例建模的最主要功能就是用来表达系统的功能性需求或行为.用例图重点描述用户需求. 它描述需求.用户和主要组件之间的关系. 它不 ...
- FRM-40400:事务完成:已应用和保存X条记录"消息框不显示处理方法
oldmesl := :system.message_level; :system.message_level :;--不显示长度超过25的信息 do_key('COMMIT_FORM'); :sys ...
- 二十四、JDK1.5新特性---泛型
由于本人认知有限,泛型在使用上没有太大压力,但是尚未具备详细介绍泛型的能力,因此本文只是粗略的描述泛型的相关知识,在以后的学习过程中会对这篇文章进行修改,希望这篇文章不会给读者带来迷惑,特此声明 什么 ...
- http错误码大全?
响应码由三位十进制数字组成,它们出现在由HTTP服务器发送的响应的第一行.响应码分五种类型,由它们的第一位数字表示:1.1xx:信息,请求收到,继续处理2.2xx:成功,行为被成功地接受.理解和采纳3 ...
- XML Schema choice 元素
XSD : <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:sch="http://w ...