2019独角兽企业重金招聘Python工程师标准>>>

#!/usr/bin/env python# Copyright (C) 2010, Adam Fourney <afourney@cs.uwaterloo.ca>
#
# This file is part of Adaptable GIMP
#
# Adaptable GIMP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# import sys, subprocess, socket, os, errno, random, hashlib, time, reif sys.platform == 'win32':from threading import Threadimport arrayclass Value:def __init__(self, typecode, arg):self.__arr = array.array(typecode, [arg])def getv(self):return self.__arr[0]def setv(self, val):self.__arr[0] = valvalue = property(getv, setv)else:from multiprocessing import Process, Value# CONSTANTS
PROXY_TO         = 'www.uwaterloo.ca'
HOST             = '127.0.0.1'
PREFERRED_PORT   = 8080
HEARTBEAT_PERIOD = 15
APPLICATION      = './gimp-2.6.exe' if sys.platform == 'win32' else './gimp-2.6'#####################################################################def main():thread_q       = []shutdown       = Value('i', 0)is_online      = Value('i', 1) # Set up the sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# Try finding a free port to listen on. # Stop after 10 tries.tries = 10port = PREFERRED_PORTwhile (tries > 0):tries = tries - 1try:s.bind((HOST, port))s.listen(5)print "Listening on port {0}".format(port)breakexcept socket.error, (err, msg):if (tries == 0):raiseelif (err == errno.EADDRINUSE):port = random.randint(1024, 49151)continueelse:raise# Set socket timeouts.settimeout(0.5)# Spawn the heartbeatheartbeat_thread = spawn_best_thread(target=start_heartbeat, args=(shutdown,is_online))heartbeat_thread.start()# Spawn our processapp_thread = spawn_best_thread(target=spawn_app, args=(shutdown,port))app_thread.start()# Handle incoming connectionswhile shutdown.value == 0:# Poll the children and reap zombiesnew_q = []for p in thread_q:if p.is_alive():new_q.append(p)thread_q = new_q# Accept a new connection try:conn, addr = s.accept()except socket.timeout:continueexcept socket.error, err:if (err == errno.EINTR):continueelse:raise# Service the request in a new threadconn.settimeout(None)p = spawn_best_thread(target=service_request, args=(conn,is_online))thread_q.append(p)p.start()s.close()#####################################################################def spawn_best_thread(target, args):if sys.platform == 'win32':return Thread(target=target, args=args)else:return Process(target=target, args=args)#####################################################################def start_heartbeat(shutdown, is_online):sleep_for = 0while shutdown.value == 0:# Sleep for half a second at a time to allow for checking of the# shutdown condition.if (sleep_for > 0):time.sleep(0.5)sleep_for = sleep_for - 0.5continue# Do actual workstart_time = time.clock()previous_status = is_online.valuenew_status = previous_statustry:client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client.settimeout(HEARTBEAT_PERIOD)client.connect((PROXY_TO, 80))client.sendall("HEAD / HTTP/1.1\r\nHost: {0}\r\nConnection: close\r\n\r\n".format(PROXY_TO))response = ""while 1:data = client.recv(1024)if not data:breakresponse += dataif re.search('^HTTP\/\d\.\d\s+200\s+OK', response):new_status = 1else:new_status = 0except socket.error: new_status = 0except socket.timeout: new_status = 0# Shutdown and close the connection, but report no errorstry: client.shutdown(socket.SHUT_RDWR);except socket.error: passtry: client.close()except socket.error: passif new_status != previous_status:print "Connection status changed. Now {0}".format('Online' if new_status else 'Offline') is_online.value = new_status# Arrange to sleep a littlesleep_for = HEARTBEAT_PERIOD - (time.clock() - start_time)#####################################################################def service_request(conn, is_online):# Read the request, respond and exit.request= ""while 1:data = conn.recv(1024)if not data:breakrequest += data# Requests are terminated by the following sequencepos = request.find("\r\n\r\n")if (pos > -1):data = data[0:pos+4]break response = make_request(request, is_online)conn.sendall(response)try:conn.shutdown(socket.SHUT_RDWR);except socket.error:passconn.close()#####################################################################def make_request(data, is_online):# Split the request into lineslines = data.split("\r\n")if data.endswith("\r\n"):lines.pop()# Hash the first line of the request for use as a keyfirst_line = lines[0];key = hashlib.md5(first_line).hexdigest()# Check for special PROXY messagesif first_line == "PROXY GET STATUS":status_str = "Online" if is_online.value > 0 else "Offline"return "Status: {0}\r\n\r\n".format(status_str)# Exit early if we are offlineif is_online.value == 0:return read_from_cache(key)# Modify the request for proxyingdata = "";for line in lines:if line.startswith('Connection:'):data = data + 'Connection: close' + "\r\n"elif line.startswith('Host:'):data = data + 'Host: {0}'.format(PROXY_TO) + "\r\n"else: data = data + line + "\r\n"# Try to fetch from the server, but fall back on the cache if we're offline try:client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client.settimeout(HEARTBEAT_PERIOD)client.connect((PROXY_TO, 80))client.sendall(data)except: return read_from_cache(key)# Read the responseresponse = ""while 1:data = client.recv(1024)if not data:breakresponse += dataclient.close()# Cache the response and returnwrite_to_cache(key, response)return response###################################################################### Read a response from the cache. Return 404 if there is a problem.
def read_from_cache(key):try:f = open("web_cache/{0}.tmp".format(key), "r")f_data = f.read()f.close()except IOError as (errnum, strerror):if (errnum == errno.ENOENT):response = """HTTP/1.1 404 Not Found\r
Content-Type: text/html\r
Connection: close\r
Content-Length: 78\r
\r
\r
<HTML><HEAD><TITLE>404</TITLE></HEAD><BODY>Page Not Found: 404</BODY></HTML>"""return responseelse:raisereturn f_data ###################################################################### Write a response to the cache. Create a web_cache directory if required.
def write_to_cache(key, response):if not os.path.isdir('web_cache'):os.mkdir('web_cache')f = open('web_cache/{0}.tmp'.format(key), 'w')                    f.write(response)                    f.close() ###################################################################### Spawn the main process
def spawn_app(shutdown, port):os.environ['AGIMP_PROXY_PORT'] = str(port)subprocess.call([APPLICATION])shutdown.value = 1   ######## CALL MAIN ########if __name__ == '__main__':main()

转载于:https://my.oschina.net/u/1385797/blog/174017

http代理的脚本http_proxy.py相关推荐

  1. Kali Linux 2017.1脚本gerix.py修复

    Kali Linux 2017.1脚本gerix.py修复 Gerix是一款优秀的图形界面的无线渗透工具.从Kali Linux 2016.2开始,该工具在Kali Linux中运行就存在一些问题.在 ...

  2. 【Android 逆向】APK 文件处理脚本 ApkTool.py ( 脚本简介 | 用法 | 分析 APK 文件 )

    文章目录 一.APK 文件处理脚本 ApkTool.py 二.ApkTool.py 脚本用法 三.ApkTool.py 脚本分析 APK 输出结果 一.APK 文件处理脚本 ApkTool.py Ap ...

  3. TF之VGG系列:利用预先编制好的脚本data_convert .py文件将图片格式转换为tfrecord 格式

    TF之VGG系列:利用预先编制好的脚本data_convert .py文件将图片格式转换为tfrecord 格式 目录 转换代码 转换后的结果 转换代码 python data_convert2tfr ...

  4. loadrunner代理录制脚本方法介绍

    LR使用代理录制脚本介绍 使用lr录制浏览器请求时,常常出现无法打开浏览器的现象.使用lr自带的代理,可以有效的解决该问题,且支持的浏览器不再限于IE.火狐,甚至可以录制手机浏览器发出的请求: 代理需 ...

  5. [转载] python中断响应_用Python脚本监测.py脚本的进程状态,并实现中断重启。

    参考链接: Python中断并继续 用Python脚本监测.py脚本的执行状态,并实现中断重启. #!/usr/bin/python # -*- coding:utf-8 -*- import sub ...

  6. linux 谷歌浏览器设置代理_浏览器自带代理服务器配置脚本

    Firefox 可以利用代理服务器配置软件来配置代理服务器.其实在浏览器里面可以利用一个标准的代理服务器配置脚本来自己控制代理服务器的使用.比如下面的例子. function FindProxyFor ...

  7. Loadrunner11使用代理录制脚本

    1.使用代理录制脚本可以解决: 录制时浏览器打不开.录制脚本为空的问题,或者被测系统本身兼容不了IE8,只能兼容更高版本浏览器的这种情况. 2.使用Loadrunner代理录制的原理: 启动Loadr ...

  8. JMeter4.0使用笔记 使用Badboy录制脚本,使用代理录制脚本

    JMeter可以用于测试静态和动态资源例如静态文件.Java 小服务程序.CGI 脚本.Java 对象. 数据库, FTP 服务器, 等等.JMeter 可以用于对服务器.网络或对象模拟巨大的负载,来 ...

  9. cocos2d-x 3.1 编译脚本android-build.py

    写在前面: 前段时间下载了cocos2d-x 3.1,按照官网的教程,配置环境,编译打包,走了一遍,感觉不错,顺便发现其中用了很多python的脚本文件,比如今天要说的android-build.py ...

最新文章

  1. UITextField长度限制的写法
  2. 13Flyweight(享元)模式
  3. CNN更新换代!性能提升算力减半,还即插即用(附论文)
  4. ERP_Oracle Erp 11i 和 R12的区别概述(概念)
  5. python 关于异常处理 try...except... 的两个案例
  6. 面试中get和post的区别
  7. windows下配置mysql主从复制_Windows下MySQL主从复制的配置方法
  8. php抓取带帐号密码,PHP实现抓取迅雷VIP账号的方法_PHP
  9. 首先不谈C语言,我们先来谈谈编程工具
  10. coding4fun比赛总结
  11. Spring中将BeanDefinition注册到IOC容器中
  12. Jmeter负载和压力测试
  13. selenium 三种断言以及异常类型
  14. [转载] python学习笔记——@property装饰器
  15. TP5模型修改器和读取器
  16. 使用Dotfuscator混淆winphone8应用XAP
  17. 基于sisotool极点配置PI参数及基于Plecs的三相电压源逆变器仿真
  18. Redis安装教程(vmware虚拟机上)
  19. SuperMap 三维产品白皮书
  20. 记一次配置深信服设备的过程

热门文章

  1. Hive:hive is not allowed to impersonate anonymous
  2. Team Foundation Server (TFS) 2015 安装指导
  3. java 十进制 左移,java移位运算符之十进制转二进制
  4. Spring事务详解与使用
  5. oracle 导出数据 utl,使用utl_file做选择性数据导出
  6. osm 搭建离线地图_使用离线OSM离线OpenLayers Web应用程序
  7. Java并发包中Semaphore的工作原理、源码分析及使用示例
  8. 互联网晚报 | 3月26日 星期六 |​ 竞拍规则优化,部分城市土地市场有所回暖;​​武汉房贷利率下调...
  9. 公司为什么宁愿花11K月薪招新人,也不愿意花9K的月薪留住老员工?
  10. 分享一个数据产品的PRD