Python实现代理服务器
2021/8/25 11:06:53
本文主要是介绍Python实现代理服务器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#coding=utf⑻ import socket import select import sys import threading import time import logging import os logsDir = "logs" if not os.path.isdir(logsDir):
os.mkdir(logsDir) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:% M:%S', filename='logs/logs.log', filemode='a') #C的IP和端口 to_addr = ('127.0.0.1', 8087) maxConnetions = 32 class Proxy:
def __init__(self, addr): self.proxy = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.proxy.bind(addr) self.proxy.listen(maxConnetions) self.inputs = {self.proxy:None} self.route = {} def serve_forever(self)
info('proxy listen...') while 1: readable, _, _ = select.select(list(self.inputs.keys()), [], []) for self.sock in readable: if self. sock
== self.proxy: self.on_join() else: try: data = self.sock.recv(8192) except Exception, e: logging.error(str(e)) self.on_quit()
self.on_quit() else: try: self.route[self.sock].send(data) except Exception, e: logging.error(str(e)) self.on_quit() continue def on_join(self):
client, addr = self.proxy.accept() logging.info("proxy client" + str(addr) + 'connect') forward = socket.socket(socket.AF_INET, socket .SOCK_STREAM) try:
forward.connect(to_addr) except Exception, e: logging.error(str(e)) client.close() return self.inputs [client] = None self.inputs [forward] =
None self.route [client] = forward self.route[forward] = client #删除连接 def on_quit(self): ls = [self.sock] if self.sock in self.route: ls.append(self.route[self.sock] )
for s in ls: if s in self.inputs: del self.inputs[s] if s in self.route:del self.route[s] s.close() if __name__ == "__main__": try: Proxy(('', 8192)).serve_forever() KeyboardInterrupt, e: logging.error("KeyboardInterrupt" + str( e))
这篇关于Python实现代理服务器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型
- 2024-12-23使用python部署一个usdt合约,部署自己的usdt稳定币
- 2024-12-20Python编程入门指南
- 2024-12-20Python编程基础与进阶
- 2024-12-19Python基础编程教程
- 2024-12-19python 文件的后缀名是什么 怎么运行一个python文件?-icode9专业技术文章分享
- 2024-12-19使用python 把docx转为pdf文件有哪些方法?-icode9专业技术文章分享
- 2024-12-19python怎么更换换pip的源镜像?-icode9专业技术文章分享