`
newton21012915
  • 浏览: 61055 次
  • 性别: Icon_minigender_1
  • 来自: 长春
社区版块
存档分类
最新评论

python实现proxy基于python 3.3

阅读更多
源码来自于网上,使用python 2.7,修改了几处代码,在python 3.3下成功运行。
# -*- coding: cp1252 -*-
# <PythonProxy.py>
#
#Copyright (c) <2009> <F¨¢bio 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¨¢bio Domingues - fnds3000 in gmail.com> <MIT Licence>

                  **************************************
                 *** Python Proxy - A Fast HTTP proxy ***
                  **************************************

Neste momento este proxy ¨¦ um Elie Proxy.

Suporta os m¨¦todos HTTP:
 - OPTIONS;
 - GET;
 - HEAD;
 - POST;
 - PUT;
 - DELETE;
 - TRACE;
 - CONENCT.

Suporta:
 - Conex?es dos cliente em IPv4 ou IPv6;
 - Conex?es ao alvo em IPv4 e IPv6;
 - Conex?es todo o tipo de transmiss?o 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?o, ou simplesmente quebrar a liga??o;
 - Criar um gestor de erros;
 - Criar ficheiro log de erros;
 - Colocar excep??es nos s¨ªtios onde ¨¦ previs¨ªvel a ocorr¨ºncia de erros,
     p.e.sockets e ficheiros;
 - Rever tudo e melhorar a estrutura do programar e colocar nomes adequados nas
     vari¨¢veis e m¨¦todos;
 - Comentar o programa decentemente;
 - Doc Strings.

Funcionalidades futuras:
 - Adiconar a funcionalidade de proxy an¨®nimo e transparente;
 - Suportar FTP?.


(!) Aten??o o que se segue s¨® tem efeito em conex?es n?o CONNECT, para estas o
 proxy ¨¦ sempre Elite.

Qual a diferen?a entre um proxy Elite, An¨®nimo e Transparente?
 - Um proxy elite ¨¦ totalmente an¨®nimo, o servidor que o recebe n?o consegue ter
     conhecimento da exist¨ºncia do proxy e n?o recebe o endere?o IP do cliente;
 - Quando ¨¦ usado um proxy an¨®nimo o servidor sabe que o cliente est¨¢ a usar um
     proxy mas n?o sabe o endere?o IP do cliente;
     ? enviado o cabe?alho 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?o enviados os cabe?alhos HTTP "Proxy-agent" e "HTTP_X_FORWARDED_FOR".

"""

import socket, _thread, select

__version__ = '0.1.0 Draft 1'
BUFLEN = 4096
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).decode()
            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)
        strs1 = HTTPVER+' 200 Connection established\nProxy-agent: %s\n\n' % VERSION
        self.client.send(strs1.encode())
        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)
        strs = '%s %s %s\n%s' % (self.method, path, self.protocol, self.client_buffer)
        self.target.send(strs.encode())
        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='10.1.11.118', port=9000, 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库 | zope.proxy-4.2.1-py3.3-win-amd64.egg

    `zope.proxy-4.2.1-py3.3-win-amd64.egg`这个文件表明该库版本为4.2.1,适用于Python 3.3版本,并且是为Windows AMD64架构编译的。如果你的开发环境满足这些条件,可以直接解压使用。 总结来说,`zope.proxy`是一个...

    PyPI 官网下载 | zope.proxy-4.1.0.win-amd64-py3.3.exe

    标题中的"PyPI 官网下载 | zope.proxy-4.1.0.win-amd64-py3.3.exe"表明我们正在讨论的是Python生态系统中的一个组件,它可以从Python的官方包索引(PyPI)获取。PyPI是Python程序员分享和分发自己编写的模块、库和...

    Python库 | lazy_object_proxy-0.1.0-cp33-none-win_amd64.whl

    `cp33` 指的是它兼容 Python 3.3 版本,`none` 表示它不依赖特定的 C 库,`win_amd64` 则表示这个版本是为 Windows 操作系统64位架构设计的。因此,这个 `.whl` 文件是一个预编译的 Python 软件包,可以直接在符合...

    python3.6.5参考手册 chm

    What’s New In Python 3.3 Summary – Release highlights PEP 405: Virtual Environments PEP 420: Implicit Namespace Packages PEP 3118: New memoryview implementation and buffer protocol documentation ...

    Python远程方法调用实现过程解析

    在Python中实现RPC可以通过多种方式,本文采用基于`multiprocessing`模块的实现方案。具体来说,使用该模块中的`Connection`类来进行数据传输,利用`json`模块进行数据的序列化和反序列化。 ##### 3.2 服务端实现 ...

    PyPI 官网下载 | zope.proxy-4.2.1-py3.3-win-amd64.egg

    资源来自pypi官网。 资源全名:zope.proxy-4.2.1-py3.3-win-amd64.egg

    Python Cookbook, 2nd Edition

    Recipe 3.3. Calculating Time Periods in a Date Range Recipe 3.4. Summing Durations of Songs Recipe 3.5. Calculating the Number of Weekdays Between Two Dates Recipe 3.6. Looking up Holidays ...

    Python入门网络爬虫之精华版

    Scrapy是一个基于Twisted的开源的Python爬虫框架,在工业中应用非常广泛。 相关内容可以参考基于Scrapy网络爬虫的搭建,同时给出这篇文章介绍的微信搜索爬取的项目代码,给大家作为学习参考。 参考项目:使用...

    mcbot:用于 mc.ruree.net 的 Minecraft 服务器机器人

    py3k 分支的 Python 3.3 或更高版本(注意:Ubuntu 13.04 已经提供 Python 3.3) 主分支的 Python 2.7 或更高版本 libzmq-dev pyzmq(使用easy_install ; pip目前不工作) 通过$ gcc 0proxy.c -o 0

    使用Nginx_Supervisor_tornado搭建web服务.pdf

    Tornado基于Python编写,支持非阻塞I/O模型,可以处理大量并发请求而不会造成服务器资源耗尽。安装Tornado可以通过Python的`pip`工具进行,例如: ```bash tar xvzf tornado-2.2.tar.gz cd tornado-2.2 python setup...

    Accelerated-ES6-Training-:Packt发布的ES6加速培训的代码存储库-源码

    您将学到什么从Docker容器中的Jupyter Notebook设置并使用带有Python 3的OpenCV 3.3 使用操纵技术执行简单的计算机视觉任务建立Instagram风格的图像过滤器调整亮度,饱和度和图像色调以创建Instagram风格的滤镜批量...

    RPC的实现

    例如,在Google的Protocol Buffers中,`.proto`文件就是一种IDL文件,它可以被编译成多种语言的源代码,如C++、Java或Python等。 **示例**: ```protobuf message Person { required int32 id = 1; required ...

    精通Odoo开发和使用

    3.3 网页显示 node.js 方面 11 3.4 其他问题 12 3.5 通过命令行运行时的配置 12 3.5.1 –xmlrpc-port=8888 12 3.5.2 –addons-path=addons 12 3.5.3 数据库的一些配置 13 3.5.4 –save 13 3.6 将安装环境封装起来 13...

    Ubuntu16.04安装配置jupyterhub

    为了实现基于GitHub的OAuth验证,首先需要在GitHub上创建OAuth application。 - 进入GitHub个人资料页面:`Settings &gt; OAuth Applications` - 填写必要的信息,如授权回调URL:`...

    thedumpster:thedumpster 是一种工具,它使用 google 及其针对特定域的傻瓜进行被动侦察

    Python - 3.3 PyQuery - 去做: 添加对使用 theharvester 域结果的支持 添加更多的傻瓜 更好地划分傻瓜 注释? 错误? 要求? 变更日志 v 1.3 添加了 Pastebin 转储搜索。 v 1.2 使用 Google dorks 的管理...

    敏捷软件开发:原则、模式与实践.pdf

    3.3 迭代计划 3.4 任务计划 3.5 迭代 3.6 结论 参考文献 第四章 测试 4.1 测试驱动的开发方法 4.2 验收测试 4.3 结论 参考文献 第五章 重构 5.1 素数产生程序一个简单的重构示例 5.2 结论 参考文献 第六章 一次编程...

    Nginx模块参考手册中文版.pdf

    实现基于请求频率的访问限制,防止恶意攻击。 #### 3.17 日志模块(Log) 记录服务器运行状态和访问日志,便于监控和故障排查。 #### 3.18 Map模块(Map) 构建变量映射表,用于复杂的条件判断。 #### 3.19 ...

    ariantxaStore

    Ariantxa商店和python con框架Django的所有应用程序都在网上发布。 因斯塔兰多 使用Ariantxan商店的El administrador de paquetes para安装。 拼装安装程序 asgiref == 3.3 . 1 astroid == 2.5 . 1 Django == 3.1 . ...

Global site tag (gtag.js) - Google Analytics