Use PYTHON to write an ORACLE proxy server

tags: python  proxy  tns  database  oracle

Sometimes, we do not want to directly expose our database to an unsafe environment. However, in the actual application process, there is indeed a practical need to connect to the database from an insecure environment. There are of course a lot of good ways to solve such a requirement that meet the safety management regulations. The reason why I want to use a proxy is because in addition to the proxy, I also want to customize the audit function for database operations (by analyzing the TNS protocol and parsing the client input message , Can save the client operation commands or SQL statements, and block dangerous operations, play a role in monitoring before and after analysis).

The complete python code is as follows:

# -*- coding: utf-8 -*-
from __future__ import print_function
import socket, thread, select, re

HEADLEN = 8
TIMEOUT = 300  # time out
HOST, PORT = "0.0.0.0", 8777  # Proxy server address, port
TNS_HOST, TNS_PORT = "192.168.100.10", 1521  # oracle server address, port
WHITE_ADDRESS = r"192\.168\.1[012]\."  # Allow access to the IP segment

class ConnectionHandler:
    def __init__(self, connection, address, timeout, tns_host, tns_port):
        self.address = address
        self.tns_host, self.tns_port = tns_host, tns_port
        self.client = connection
        if re.match(WHITE_ADDRESS, connection.getpeername()[0]) is None:
            self.client.close()
            return
        self.timeout = timeout
        self.method_def = dict(zip([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
                                   ['CONNECT', 'ACCEPT', 'ACK', 'REFUTE', 'REDIRECT', 'DATA', 'NULL', 'OTHER1', 'ABORT',
                                    'OTHER2', 'RESEND', 'MARKER', 'ATTENTION', 'CONTROL']))
        self.client_buffer = self.__get_buffer__(self.client)
        self.transfer()
        self.client.close()
        self.target.close()

    def __get_method__(self, buf):
        method = self.method_def.get(ord(buf[4])) \
            if len(buf) >= 5 and self.method_def.has_key(ord(buf[4])) else "NONE"
        return method

    def __get_buffer__(self, soc):
        header = soc.recv(HEADLEN)
        bufferLen = ord(header[0]) * 256 + ord(header[1]) - HEADLEN if len(header) >= 2 else 0
        data = header + soc.recv(bufferLen) if bufferLen > 0 else header
        return data

    def __send_buffer__(self, soc, buf):
        soc.send(buf)

    def __connect_target__(self):
        self.client_buffer = self.client_buffer.replace(str(self.address[1]), str(self.tns_port))  # Change port
        (soc_family, _, _, _, address) = socket.getaddrinfo(self.tns_host, self.tns_port)[0]
        self.target = socket.socket(soc_family)
        self.target.connect(address)

    def transfer(self):
        method = self.__get_method__(self.client_buffer)
        if method == 'CONNECT':
            self.__connect_target__()
        self.__send_buffer__(self.target, self.client_buffer)
        self.client_buffer = ''
        self.__read_write__()

    def __read_write__(self):
        time_out_max = self.timeout / 2
        socs = [self.client, self.target]
        count = 0
        while 1:
            try:
                count += 1
                (recv, _, error) = select.select(socs, [], socs, 2)
                if error:
                    break
                if recv:
                    for in_ in recv:
                        data = self.__get_buffer__(in_)
                        out = self.target if in_ is self.client else self.client
                        if data:
                            self.__send_buffer__(out, data)
                            count, data = 0, ""
                if count == time_out_max:
                    break
            except Exception, e:
                break

def start_server(host=HOST, port=PORT, timeout=TIMEOUT, handler=ConnectionHandler, tns_host=TNS_HOST,
                 tns_port=TNS_PORT):
    soc = socket.socket(socket.AF_INET)
    soc.bind((host, port))
    soc.listen(0)
    print(u"Agent service started:% s:% d" % (host, port))  # debug
    while 1:
        thread.start_new_thread(handler, soc.accept() + (timeout, tns_host, tns_port,))

if __name__ == '__main__':
    start_server()

Not only the oracle, the code is slightly modified, but it can also be used to connect to any other database or some other application that is not a database. Of course, this way of writing is different from directly connecting to a database. If you do not interact with the database for a long time after logging in, the connection will be disconnected.

Intelligent Recommendation

Use of proxy server

The following is to make a virtual host in the configuration of nginx by proxy; 1. Add the following code in nginx.conf: 2. Create a new conf.d directory 3. There are two configuration files in the co...

Configuration and use of proxy server

One, install stunnel 1. Download stunnel-5.42-win32-installer.exe 2. Installation Click the installation file and continue to next until a small black window appears: At this time we have to fill in s...

Python crawler server proxy

Use a proxy server to crawl web pages:...

Proxy server for python crawler

Sometimes using the same IP to crawl the homepage of a website, after a long time it will be blocked by the web server, and we can find some proxy servers (Proxy server) Code: A. Useurllib.request.Pro...

Python reptile proxy server

Agent's common function 1. Break through itself IP Access restrictions, access to foreign sites. 2. Access some units or group internal resources Expansion: A University FTP ( The premise is that the ...

More Recommendation

How does the Python requests library use a proxy server?

When doing crawling, sometimes you need to use a proxy server to access some websites. At this time, you can use a library like pysocks to implement it through socks5. Install pysocks pip install pyso...

python-Quickly use urllib to crawl web pages (6-proxy server)

Through the above learning, we found that there will be problems when crawling 1. The website cannot be crawled, that is, the website is set to anti-crawl 2. Character code problem 3. The crawling tim...

Python and requests module use proxy server to achieve Weibo access

Python3.6.1  requests2.18.4  scrapy,beautifulsoup Development tools sublime text 3 (This Weibo is the original blogger, if you want to repost, please indicate the link to the original b...

Python-read and write Oracle

In recent projects, Python needs to use Oracle to call Oracle for reading and writing operations. How not to talk about performance first, there are ways to tune it later. Now record the code and note...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top