Python implements a simple TCP proxy server

Source: Internet
Author: User
This article describes the Python implementation of a simple TCP Proxy server method, share to everyone for your reference.

The specific implementation code is as follows:

#-*-Coding:utf-8-*-"Filename:rtcp.py@desc: Using Python's socket port forwarding for remote maintenance if the connection is not remote, it will sleep 36s, up to 200 (i.e. two hours) @usage:. /rtcp.py stream1 Stream2stream is: L:port or c:host:portl:port indicates that the listener specifies the local port C:host:port, which listens for remote specified ports @author:watercloud, ZD, Knownsec team@web:www.knownsec.com, blog.knownsec.com@date:2009-7 "Import Socketimport sysimport Threadingimport Timestreams = [None, none] # store two data streams (all Socketobj objects) that require data forwarding debug = 1 # Debug State 0 or 1def _usage (): print ' usage:./rtcp.py s tream1 Stream2\nstream:l:port or C:host:port ' def _get_another_stream (num): "' gets another stream object from streams, and if it is currently empty, wait for ' if num = = 0:num = 1 elif num = = 1:num = 0 else:raise "ERROR" while true:if streams[num] = = ' Quit ': print ("Can ' t connect to th  E Target, quit now! ") Sys.exit (1) if streams[num]! = None:return Streams[num] Else:time.sleep (1) def _xstream (num, s1, s2): "Exchange two streams of data num for Current stream number, mainly used for debugging purposes, distinguish two loop state. "' Try:while True: #注意, the recv function will block until the end of the pair is closed completely (it takes time to close after close, the quickest way to close is Shutdow) buff = S1.RECV (1024x768) If debug > 0:  Print num, "recv" If len (buff) = = 0: #对端关闭连接, cannot read data print num, "one closed" break s2.sendall (Buff) if debug > 0:p Rint num, "sendall" Except:print num, "One connect closed." Try:s1.shutdown (socket. SHUT_RDWR) s1.close () Except:pass try:s2.shutdown (socket). SHUT_RDWR) s2.close () except:pass streams[0] = none streams[1] = none print num, "CLOSED" Def _server (Port, num): ' Processing service , NUM is the stream number (number No. 0 or 1th) ' SRV = Socket.socket (socket.af_inet, socket.  Sock_stream) Srv.bind ((' 0.0.0.0 ', port)) Srv.listen (1) while true:conn, addr = srv.accept () print "Connected from:", addr Streams[num] = conn # put the Stream object s2 = _get_another_stream (num) # Get the other end stream object _xstream (NUM, conn, S2) def _connect (host, Port, Nu m): ' Processing the connection, NUM is the stream number (number No. 0 or 1th) @note: If the connection is not remote, will sleep 36s, up to 200 (i.e. two hours) "Not_connet_time = 0 Wait_time = try_cnt = 1 True:if not_connet_time > Try_cnt:streams[num] = ' Quit ' Print (' Not connected ') return None conn = socket. Socket (socket.af_inet, socket. SOCK_STREAM) Try:conn.conNect (host, port) except Exception, E:print (' Can not connect%s:%s! '% (host, port)) Not_connet_time + = 1 time.sleep  (wait_time) Continue print "connected to%s:%i"% (host, port) Streams[num] = conn #放入本端流对象 s2 = _get_another_stream (num) #获取另一端流对象 _xstream (NUM, conn, s2) if __name__ = = ' __main__ ': If Len (sys.argv)! = 3: _usage () sys.exit (1) tlist = [] # thread List , eventually storing two thread objects targv = [sys.argv[1], sys.argv[2]] for i in [0, 1]: s = targv[i] # Stream Description C:ip:port or L:port SL = S.split (' : ') If Len (SL) = = 2 and (sl[0] = = ' l ' or sl[0] = = ' L '): # l:port t = Threading. Thread (Target=_server, args= (int (sl[1]), i)) Tlist.append (t) elif len (SL) = = 3 and (sl[0] = = ' C ' or sl[0] = = ' C '): # C:ho St:port t = Threading. Thread (Target=_connect, args= (sl[1], int (sl[2]), i)) tlist.append (t) Else: _usage () sys.exit (1) for T in Tlist:t.start () for T in Tlist:t.join () sys.exit (0)

Full instance code click here to download this site.

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.