Http/Https代理Python实现
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
对Python感兴趣,工作之余,参照部分文档初步实现了HTTP/HTTPs代理。(代码比较凌乱,各位留情。)
使用Fiddler调试。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import socketimport timeimport threading
BUFSIZE=1024class Access_to_Host(object):def handler(self,conn,addr):self.conn=connself.addr=addrall_src_data,hostname,port,ssl_flag=self.get_dst_host_from_header(self.conn,self.addr)all_dst_data=self.get_data_from_host(hostname,port,all_src_data,ssl_flag)if all_dst_data and not ssl_flag:#self.send_data_to_client(self.conn,all_dst_data)self.ssl_client_server_client(self.conn,self.conn_dst,all_dst_data)elif ssl_flag:sample_data_to_client=b"HTTP/1.0 200 Connection Established\r\n\r\n"# print("\nSSL_Flag-1")#self.send_data_to_client(self.conn,all_dst_data)#print("SSL_Flag-2")self.ssl_client_server_client(self.conn,self.conn_dst,sample_data_to_client)#print("\nSSL_Flag-3")else:print('pls check network. cannot get hostname:'+hostname)#self.conn.close()def ssl_client_server(self,src_conn,dst_conn):self.src_conn=src_connself.dst_conn=dst_conn while True:###get data from clienttry:ssl_client_data=self.src_conn.recv(BUFSIZE)except Exception as e:print("client disconnct ")print(e)self.src_conn.close()#self.dst_conn.close()return Falseif ssl_client_data:#####send data to servertry:self.dst_conn.sendall(ssl_client_data)except Exception as e:print("server disconnct Err")self.dst_conn.close()return Falseelse:self.src_conn.close()return Falsedef ssl_server_client(self,src_conn,dst_conn):self.src_conn=src_connself.dst_conn=dst_connwhile True:###get data from servertry:ssl_server_data=self.dst_conn.recv(BUFSIZE)except Exception as e:print("server disconnct ")self.dst_conn.close()return Falseif ssl_server_data:#####send data to clienttry:self.src_conn.sendall(ssl_server_data)except Exception as e:print("Client disconnct Err")self.src_conn.close()return Falseelse:self.dst_conn.close()return Falsedef ssl_client_server_client(self,src_conn,dst_conn,all_dst_data):self.src_conn=src_connself.dst_conn=dst_conntry:#print(all_dst_data)self.src_conn.sendall(all_dst_data)except Exception as e:print(e)print("cannot sent data(HTTP/1.0 200) to SSL client")return Falsethreadlist=[]t1=threading.Thread(target=self.ssl_client_server,args=(self.src_conn,self.dst_conn))t2=threading.Thread(target=self.ssl_server_client,args=(self.src_conn,self.dst_conn))threadlist.append(t1)threadlist.append(t2)for t in threadlist:t.start()#t.join()######线程控制,等待线程结束后,远程主机关闭socket后,客户端到主机的socket也不需要再做任何操作了。while not self.dst_conn._closed:time.sleep(1)self.src_conn.close()def get_src_client(self):self.src_ip=self.s_src.getpeername()return self.src_ipdef send_data_to_client(self,conn_src,data):self.conn_src=conn_srctry:self.conn_src.sendall(data)except Exception as e:print(e)print("cannot sent data to client")return False#self.conn_dst.close()def get_dst_host_from_header(self,conn_sock,addr):self.s_src=conn_sockself.addr=addrheader=""ssl_flag=Falsewhile True:#print("Loop Loop Loop")header=self.s_src.recv(BUFSIZE)if header :#####header的一行含有CONNECT,即为SSL(HTTPS)indexssl=header.split(b"\n")[0].find(b"CONNECT")# print("indexsll:"+str(indexssl))if indexssl>-1:#####CONNECT===7 +8 前面一个空格hostname=str(header.split(b"\n")[0].split(b":")[0].decode())hostname=hostname[indexssl+8:]port=443ssl_flag=Truereturn header,hostname,port,ssl_flagindex1=header.find(b"Host:")index2=header.find(b"GET http")index3=header.find(b"POST http")if index1>-1:indexofn=header.find(b"\n",index1)##host:===5host=header[index1+5:indexofn]elif index2>-1 or index3>-1:###no host sample :'GET http://saxn.sina.com.cn/mfp/view?......host=header.split(b"/")[2]else: print("src socket host:")print(self.s_src.getpeername())print("cannot find out host!!:"+repr(header))return breakhost=str(host.decode().strip("\r").lstrip())if len(host.split(":"))==2:port=host.split(":")[1]hostname=host.split(":")[0].strip("")else:port=80hostname=host.split(":")[0].strip("")ssl_flag=Falsereturn header,hostname,int(port),ssl_flagdef get_data_from_host(self,host,port,sdata,ssl_flag):self.conn_dst=socket.socket(socket.AF_INET,socket.SOCK_STREAM)all_dst_data=""try:self.conn_dst.connect((str(host),port))except Exception as e:print(e)print("get_data_from_host: cannot get host:"+host)self.conn_dst.close()return False#con_string="("+server+","+port+")"############https只建立链接try:if ssl_flag:return all_dst_dataelse:self.conn_dst.sendall(sdata)except Exception as e:print(e)print("cannot send data to host:"+host)self.conn_dst.close()return False# buffer=[]rc_data=self.conn_dst.recv(BUFSIZE)#####剩下的data交给线程去获取return rc_dataclass Server(object):def Handle_Rec(conn_socket,addr):print("This is Handler Fun")passdef __init__(self,host,port):print("Server starting......")self.host=hostself.port=portself.s_s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)self.s_s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)self.s_s.bind((host,port))self.s_s.listen(20)def start(self):while True:try:conn,addr=self.s_s.accept()threading.Thread(target=Access_to_Host().handler,args=(conn,addr)).start()except Exception as e:print(str(e))print("\nExcept happend")if __name__=="__main__":svr=Server("127.0.0.1",8080)svr.start()
Http/Https代理Python实现相关推荐
- python使用http、https代理
在国内利用Python从Internet上爬取数据时,有些网站或API接口被限速或屏蔽,这时使用代理可以加速爬取过程,减少请求失败,Python程序使用代理的方法主要有以下几种: (1)如果是在代码中 ...
- Could not fetch URL https://pypi.python.org/simple/: connection error: HTTPSConnectionPool(host='pyp
首先说明我本人使用的是python2.7,今天使用pycharm的的时候一直不行,我本人也是一个新手,在网上查资料的时候看到很多命令行的方法,当时我有点懵,不知道这这些的命令行的往哪里敲,所以这里多说 ...
- go get 代理 找不到包_初步看看Go1.10 支持 HTTPS 代理
Go1.10 支持 HTTPS 代理 Go1.9 出来后 6 个多月的时间,Go1.10 就被发布.新版本带来大大小小的变化(发行说明),但是我想谈谈有关 net/http 包的改变.1.10 版本支 ...
- docker代理设置ssl证书_docker - 设置HTTP/HTTPS 代理
1.设置代理原因 因公司安全限制,所有外网需配置代理后才可上网,但是因为宿主机上设置过代理,并未太过多注意此问题,之后run时报如下错误: # docker run hello-world Unabl ...
- nginx https透明代理_nginx正向https代理配置
一.前言 1.1 正向代理功能比较简单,但是原生nginx不支持https代理,如果访问https网站,会报错. # nginx代理不支持http CONNECT方法:curl: (56) Recei ...
- https://docs.python.org/3/
2019独角兽企业重金招聘Python工程师标准>>> https://docs.python.org/3/ http://python3-cookbook.readthedocs. ...
- 13. nginx四层 https代理https 前后端证书配置
使用情况 1.https代理https服务,后端与前端非同一证书. 2.想使用nginx代理来颁发合法新证书. 前提条件 准备后端证书且要与后端服务使用相同证书 准备前端证书. vim /etc/ng ...
- 简单说下HTTP代理、HTTPS代理、SOCKS代理的原理区别,charles抓包HTTPS原理
采用PROXY代理方式通讯时,都是客户只TCP/IP连接到代理,客户只和代理通讯. 代理和目标进行TCP/IP通讯,代理需要先有PROXY信息,才能知道目标服务器的地址. HTTP代理最简单!因为H ...
- 使用woo 语言开发 sockets4 sockets5 http https代理完整记录
记录下使用woo语言开发 sockets 和https代理过程 已经在gitee开源: https://gitee.com/oshine/woo_proxy 目前使用的是一个端口监听所有的代理包含ht ...
最新文章
- STM32-RCC内部总线时钟设置程序详讲
- 您的请求参数与订单信息不一致_[淘客订单检测]淘宝客订单检测接口,淘客订单查询API...
- mysql 逻辑备份导入数据库_mysql逻辑备份(mysql dump的使用)
- Redmine使用手册
- php使用curl发送请求时 添加header失效
- ext源码阅读 - DomHelper - createHtml,insertHtml
- 基于kafka的定时消息/任务服务
- winrar软件如何测试
- call function中的 exporting/importing/changing
- 虹科新品 | 需要进行高功率,大规模的测试控制?这款5A功率高密度继电器模块你一定不能错过!
- 局域网共享文件夹现在内存不足_局域网文件夹共享给指定用户的方法
- 感谢上天,我被失联2年后,终于活着从东南亚菠菜公司的技术“魔窟”逃出来了......
- 圆柱体积怎么算立方公式_圆柱体积怎么算 求圆柱体积的公式
- 应对焦虑的时候,需要学会一次只解决一个问题
- ❤送女朋友生日快乐祝福网页制作❤(HTML+CSS+JS)
- mysql创建学生答题系统_jsp+ssm+mysql实现的学生在线考试系统
- 微信通过JSSDK分享朋友圈
- ECharts图表坐标轴数据超出显示范围,以及坐标轴刻度标签显示不全解决方法
- 安卓新手如何学习开发一款游戏APP呢?
- 2021年中国有机颜料供需及主要企业经营分析[图]