Basic information for proxy

3 minute read

zcmd.py : command interface with proxy

#----------------------------------------------
# zcmd.py
#----------------------------------------------
import sys
import socket                   # Import socket module
from commands import *

import logging
from datetime import datetime
import os

#----------------------------------------------
# Logging
#----------------------------------------------
logger = logging.getLogger(__name__)
formatter = logging.Formatter('[%(asctime)s][%(levelname)-8s|%(filename)s:%(lineno)s] >> %(message)s')

# fileout
logpath = os.getenv('HOME') + '/zeus/log'
logfile = 'zcmd'
fileHandler = logging.FileHandler(logpath + '/' + logfile + '{:_%Y%m%d}.log'.format(datetime.now()))
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
logger.setLevel(level=logging.DEBUG)

#----------------------------------------------
# Global variables
#----------------------------------------------
global gip, gport, gsvr, gcmd

gip = '127.0.0.1'
gport = 20212
gsvr = ""
gcmd = ""

#----------------------------------------------
# Functions
#----------------------------------------------
def usage():
    print("Usage: " + sys.argv[0] + " s <port>")
    print("       " + sys.argv[0] + " c <ip> <port> <svrnm> <command>")

def run_server():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)             # Create a socket object
    host = '0.0.0.0'                # Any cf.socket.gethostname()
    s.bind((host, gport))           # Bind to the port
    s.listen(5)                     # Now wait for client connection.

    logger.info('Server listening... (Port:' + str(gport) + ")")

    while True:
        conn, addr = s.accept()     # Establish connection with client.
        logger.info('Connection from : ' + str(addr))
        data = conn.recv(4096)
        logger.info('Server received : ' + repr(data))

        cmd = str(data)
        logger.debug('Cmd : ' + cmd)

        output = getoutput(cmd) # if output is too long...

        logger.debug (output)
        conn.send(output)
        conn.close()

def run_client():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)             # Create a socket object
    print("connecting to " + gip)
    sock.connect((gip, gport))
    sock.send(gsvr+gcmd)

    buf = ""
    while True:
        buf = sock.recv(1024)
        if not buf:
            break
        sys.stdout.write(buf)

    print ""

    sock.close()
    print('connection closed')


#----------------------------------------------
# Check & Run
#----------------------------------------------
argc = len(sys.argv)
print("Starting...(Argc: " + str(argc) + ")")

if argc > 1:
    if sys.argv[1][0] == 's':
        logger.debug("server : " + sys.argv[1])
        if argc > 2:
            gport = int(sys.argv[2])
            run_server()
        else:
            usage()
            sys.exit()
    elif sys.argv[1][0] == 'c':
        print("client :" + sys.argv[1])
        print("Argc :", argc)
        if argc > 3:
            gip = sys.argv[2]
            gport = int(sys.argv[3])
            gsvr = sys.argv[4]
            print("Svr :", gsvr)
            if argc > 5:
                for idx in range(5, argc):
                    gcmd = gcmd + " " + sys.argv[idx]
                gcmd = gcmd.strip()
                print ("Cmd :", gcmd) 
            run_client()
        else:
            usage()
            sys.exit()
else:
    usage()
    sys.exit()

proxy.py : proxy and routing

#!/usr/bin/python
# This is a simple port-forward / proxy, written using only the default python
# library. If you want to make a suggestion or fix something you can contact-me
# at voorloop_at_gmail.com
# Distributed over IDC(I Don't Care) license
import socket
import select
import time
import sys

# Changing the buffer_size and delay, you can improve the speed and bandwidth.
# But when buffer get to high or delay go too down, you can broke things
buffer_size = 4096
delay = 0.0001
#forward_to = ('dvchsd01', '127.0.0.1', 20212)

forward_list = []
forward_list.append(('tstsvr01', '127.0.0.1', 20212))
forward_list.append(('tstsvr02', '172.0.0.1', 20212))

class Forward:
    def __init__(self):
        self.forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def start(self, host, port):
        try:
            self.forward.connect((host, port))
            return self.forward
        except Exception, e:
            print e
            return False

class TheServer:
    input_list = []
    channel = {}

    def __init__(self, host, port):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server.bind((host, port))
        self.server.listen(200)

    def main_loop(self):
        self.input_list.append(self.server)
        while 1:
            time.sleep(delay)
            ss = select.select
            inputready, outputready, exceptready = ss(self.input_list, [], [])
            for self.s in inputready:
                if self.s == self.server:
                    self.on_accept()
                    break

                self.data = self.s.recv(buffer_size)
                if len(self.data) == 0:
                    self.on_close()
                    break
                else:
                    self.on_recv()

    def on_accept(self):
        clientsock, clientaddr = self.server.accept()
        rlen = 0
        rdat = ""
        while True:
          data = clientsock.recv(8-rlen)
          if not data:
            continue
          rdat = rdat + data
          rlen = rlen + len(data)
          print "=========", rdat
          print data, rlen
          if rlen >= 8:
            break

        print "--- SERVER NAME ---", data
        ipaddr = ""
        port = None
        for svrnm in forward_list:
            if svrnm[0] == data:
                ipaddr = svrnm[1]
                port = svrnm[2]
                break

        if ipaddr:
            forward = Forward().start(ipaddr, port)
            if forward:
                print clientaddr, "has connected"
                self.input_list.append(clientsock)
                self.input_list.append(forward)
                self.channel[clientsock] = forward
                self.channel[forward] = clientsock
            else:
                print "Can't establish connection with remote server.",
                print "Closing connection with client side", clientaddr
                clientsock.close()

    def on_close(self):
        print self.s.getpeername(), "has disconnected"
        #remove objects from input_list
        self.input_list.remove(self.s)
        self.input_list.remove(self.channel[self.s])
        out = self.channel[self.s]
        # close the connection with client
        self.channel[out].close()  # equivalent to do self.s.close()
        # close the connection with remote server
        self.channel[self.s].close()
        # delete both objects from channel dict
        del self.channel[out]
        del self.channel[self.s]

    def on_recv(self):
        data = self.data
        # here we can parse and/or modify the data before send forward
        print data
        self.channel[self.s].send(data)

if __name__ == '__main__':
        server = TheServer('', 20212)
        try:
            server.main_loop()
        except KeyboardInterrupt:
            print "Ctrl C - Stopping server"
            sys.exit(1)

Tags:

Categories:

Updated:

Leave a comment