我需要编写应用程序来监视mac os上的所有http请求/响应。如何在Mac OS中注册代理服务器。
答案 0 :(得分:0)
我找到了一个简单的例子 - python tcp服务器重定向请求/响应和自动设置Mac OS代理设置的代码。
Python脚本取自http://www.cppfun.com/python-2-7-simple-http-proxy-server.htm,来自How to set proxy settings on MacOS using python的Mac OS代理设置配置器
import socket, sys
import os
from thread import *
max_conn = 8
buffer_size = 8192
def proxy_on(port):
os.system('networksetup -setwebproxy Ethernet '+'127.0.0.1'+' '+str(port))
def proxy_off():
os.system('networksetup -setwebproxystate Ethernet off')
def app():
try:
listen_port = int(raw_input("[*] Enter listening port(a number eg 8098):"))
proxy_on(listen_port)
start(listen_port)
except KeyboardInterrupt:
print "\n[*] User requested interrupt\n[*] Program exiting ..."
sys.exit()
def start(listen_port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', listen_port))
s.listen(max_conn)
print "[*] Init sockets ... Done"
print "[*] Sockets bind success ..."
print "[*] Proxy server success [%d]\n" % listen_port
except Exception, e:
print "\n", e
print "[*] Unable to init socket, maybe try another port"
sys.exit(2)
while True:
try:
conn, addr = s.accept()
data = conn.recv(buffer_size)
start_new_thread(conn_str, (conn, data, addr))
except KeyboardInterrupt:
s.close()
print "\n[*] Proxy server shutdown ..."
print "[*] Have a good day !"
proxy_off()
sys.exit(1)
s.close()
def conn_str(conn, data, addr):
try:
first_line = str(data).split('\n')[0]
url = first_line.split(' ')[1]
print url
host, port = get_host_and_port(url)
print host, port, data
proxy_server(host, port, conn, addr, data)
except Exception, e:
print "\n", e
print "[*] Get the http url or port fail ..."
sys.exit(1)
def get_host_and_port(url):
import urllib
_, rest = urllib.splittype(url)
host, rest = urllib.splithost(rest)
host, port = urllib.splitport(host)
if port is None:
port = 80
return host,port
def proxy_server(host, port, conn, addr, data):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(data)
while True:
reply = s.recv(buffer_size)
if len(reply) > 0:
conn.send(reply)
dat = float(len(reply))/1024.0
dat = "%.3s KB" % str(dat)
print "[*] Request done : %s => %s <=" % (addr[0], dat)
else:
break
s.close()
conn.close()
except socket.error, (value, message):
print "\n[*] Socket error %d:%s" % (value, message)
s.close()
conn.close()
sys.exit(1)
if __name__ == '__main__':
# power by cppfun.com
app()
# also you can change it yourself