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模块的扩 ...
随机推荐
- Java提高篇——Java 异常处理
异常的概念 异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的. 比如说,你的代码少了一个分号,那么运行出来结果是提示是错误java.lang.Error:如果你用Syst ...
- nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) 错误解决
今天在做LNMP的时候,启动nginx服务,无法开启,导致网页打不开.把服务从起一下发现提示错误如下: Starting nginx: nginx: [emerg] bind() to 0.0.0.0 ...
- 启动tomcat时 错误: 代理抛出异常 : java.rmi.server.ExportException: Port already in use: 1099;
错误: 代理抛出异常 : java.rmi.server.ExportException: Port already in use: 1099; nested exception is: java ...
- javascript获取当前url
在WEB开发中,许多开发者都比较喜欢使用javascript来获取当前url网址,本文就此为大家总结一下比较常用获取URL的javascript实现代码,以下示例是前面为相应实现方法,后面是获取URL ...
- oracle同一个数据库实例不同的用户之间的表、序列授权操作
1.背景:用户jtuser中有jtproduct中表A,B的同义词,在用户jtuser中向表A,B插入数据,提示“权限不够” 2.将A,B表授权给jtuser用户 $ sqlplus / as sys ...
- 在virtualbox中安装CentOS-7
当初才接触linux的时候,因为条件限制,只能在虚拟机中安装linux系统使用,由于是小白,爬了好多坑.于是决定写一篇关于在虚拟机中安装linux系统的博客.一是为了巩固自己的知识,二是希望能够对新手 ...
- js 复选框 全选都选 如果某一个子复选框没选中 则全选按钮不选中
<!DOCTYPE HTML> <html> <head> <meta charset=UTF-8> <title>js 复选框 全选都选 ...
- python学习笔记系列----(四)模块
这一章主要是叙述了python模块的概念以及包的概念,还有它们的使用:收获也是大大的. 提起python文件,经常会听到3个名词,python脚本,python模块,python包.脚本的概念是从py ...
- 3173: [Tjoi2013]最长上升子序列
原题:http://www.lydsy.com/JudgeOnline/problem.php?id=3173 题解:促使我写这题的动力是,为什么百度遍地是Treap,黑人问号??? 这题可以用线段树 ...
- 介绍Ext JS 4.2的新特性的《深入浅出Ext JS》上市
以用户为中心的时代,应用的界面外观变得越来越重要.然而,很多程序员都缺乏美术功底,要开发出界面美观的应用实属不易.Ext JS的出现,为广大程序员解决了这一难题.它有丰富多彩的界面和强大的功能,是开发 ...