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. Linux 使用本地yum源及软件包管理

    [root@node130 rh]# pwd/opt/rh[root@node130 rh]# lsrhel-server-6.4-x86_64-dvd.iso [root@node130 rh]#m ...

  2. c语言第8次作业

    #include<stdio.h> int main() { ]={}; int m; ; ;m<;m++) { a[m]=m+; !=&&a[m]%!=) n++; ...

  3. centos7 开启防火墙端口 firewalld

    systemctl start firewalld firewall-cmd --zone=public --add-port=3306/tcp --permanent firewall-cmd -- ...

  4. C# 不重复的随机数

    public int RabdomNumber() { num = new Random(Guid.NewGuid().GetHashCode()).Next(0, 40); return num; ...

  5. 一周试用yii开发一个带各种该有功能的web程序(三)

    接上篇,为什么index 模版里没有任何有关require,inculde类型关键字,却任然有我们认为“多余”的字符出现.因为在至少我的认知里html的结构该是<html><head ...

  6. photoshop学习入门:选择和处理

    昨天花了一天时间看了李涛的视频<高手之路>入门的24集,累得连写工作日报的力气都没了,19点就睡.今天4点起来,补一下记录. photoshop是个位图处理工具(别的花里胡哨的功能忽略)— ...

  7. 判断是否IPv6网络

    bool isIPV6Net(const std::string ip_v4, std::string& out_ip) { bool is_v6 = false; struct addrin ...

  8. Android 子线程测试

    private volatile boolean mStopped = false; private int i; TextView tv1; TextView tv2; @Override prot ...

  9. 浅析Java.lang.ProcessBuilder类

    最近由于工作需要把用户配置的Hive命令在Linux环境下执行,专门做了一个用户管理界面特地研究了这个不经常用得ProcessBuilder类.所以把自己的学习的资料总结一下. 一.概述      P ...

  10. html table表头斜线

    关于htnl的table的表头斜线,符合表格设计规范,<style> .biaotou { line-height: 5px; text-align: left; } .biaotou { ...