设为首页 收藏本站
查看: 413|回复: 0

[经验分享] python实现proxy基于python 3.3

[复制链接]

尚未签到

发表于 2017-4-22 13:34:04 | 显示全部楼层 |阅读模式
源码来自于网上,使用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()

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-367827-1-1.html 上篇帖子: 【Python真的很强大】md5sum in Python 下篇帖子: Python URL Shortening(Python短地址)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表