如何使用python创建代理服务器?

时间:2016-03-02 03:48:41

标签: python proxy

我一直在尝试制作允许UA欺骗的代理服务器,但它似乎不起作用,我不知道为什么。

config.py

# if you want to spoof the useragent then,
# replace "$MyAgent" with the desired agent.
# For example,
# agent="Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:44.0) Gecko/20100101 Firefox/44.0"

host="127.0.0.1"
port=8888
byte=4096
listeners=100
delay=00000.1
agent="$MyAgent"

Proxy.py

import socket, select, time, config, sys
def Print(val):
    sys.stdin.flush()
    sys.stdout.write(val)

class ProxyServer(object):
    def __init__(self):
        self._host = (config.host, config.port)
        self._socket = socket.socket()
        self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._socket.setblocking(False)
        self._agent = config.agent
        self._bytes = config.byte
        self._delay = config.delay
        self._listeners = config.listeners
        self._cons = list()
        self._log = Print

    def _bind(self):
        self._socket.bind(self._host)
        self._socket.listen(self._listeners)

    def main(self):
        self._cons.append(self._socket)
        while True:
            time.sleep(self._delay)
            rl, xl, wl = select.select(self._cons, [], [])
            for sock in rl:
                if sock == self._socket:
                    sock, ip = self._socket.accept()
                    self._on_connect()
                    self._cons.append(sock)
                elif sock == None:
                    self._socket.close()

                data = sock.recv(self._bytes)
                agent = self._get_agent_header(data)
                if not agent == "NO_AGENT":
                    agent_new = self._agent.replace("$MyAgent", agent)
                    data = data.replace(agent, agent_new)
                    sock.send(data)
                else:
                    sock.send(data)
                if not data:
                        self._on_close(sock)

    def _on_close(self, sock):
        self._cons.remove(sock)
        self._log("client dc {0} left".format(self._count()))
        sock.close()

    def _on_connect(self):
        self._log("connection made, {0} clients connected".format(self._count()))

    def _count(self):
        c = len(self._cons) - 1
        return c

    def _get_agent_header(self, data):
        pat = "User-Agent: (.+)"
        m = re.search(pat, data)
        if m:
            return m.group(0)
        else:
            return "NO_AGENT"


if __name__ == '__main__':
    server = ProxyServer()
    server._bind()
    server.main()

如果您运行此请求将无法完成。但是,一些标题将以纯文本显示。有什么我做得不对劲吗?

0 个答案:

没有答案