Python implements a simple TCP proxy server _python

Source: Internet
Author: User

This article describes the Python implementation of a simple TCP Proxy server method, share for everyone to reference.

The specific implementation code is as follows:

#-*-Coding:utf-8-*-' filename:rtcp.py @desc: Use python socket port forwarding for remote maintenance if the connection is not remote, will sleep 36s, up to 200 (that is, two hours) @usage :./rtcp.py stream1 stream2 Stream is: L:port or c:host:port indicates that listening for the specified local port L:port indicates that the remote specified port is listening @author: C:host:port, Watercloud , Knownsec team @web: www.knownsec.com, blog.knownsec.com @date: 2009-7 ' import socket import sys import threading Imp ORT time streams = [None, none] # store two data streams (all Socketobj objects) that require data forwarding debug = 1 # Debug State 0 or 1 def _usage (): print ' usage:. /rtcp.py stream1 Stream2\nstream:l:port or C:host:port ' def _get_another_stream (num): ' Get another stream object from streams, if the current is empty, wait To ' if num = = 1 Elif num = 1:num = 0 else:raise "ERROR" while true:if streams[num] = = ' quit ': P 0:num
  Rint ("can" T connect to the target, quit now! ") Sys.exit (1) if streams[num]!= none:return Streams[num] Else:time.sleep (1) def _xstream (num, s1, s2): "Swap Two
 Stream Data num is the current stream number, mainly for debugging purposes, distinguishing two loop states with. ' Try:while True: #注意, the recv function blocks until the end is completely closed (it takes a certain amount of time toCan be turned off, the quickest way to close is Shutdow) buff = S1.RECV (1024) if debug > 0:print num, "recv" If len (buff) = = 0: #对端关闭连接, data not read Prin T num, "one closed" break s2.sendall (Buff) if debug > 0:print num, "sendall" Except:print num, "one connect C

 losed. " 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 condition, NUM is stream 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 # into this end stream object s2 = _get_another_stream (num) # Get the other end stream object _xstream (NUM, conn, S2) def _connect (host , Port, num): "Process the connection, NUM is the stream number (No. 0 or 1th) @note: If the connection is not remote, will sleep 36s, up to 200 (that is two hours)" "Not_connet_time = 0 wait_time = TRY_CNT = 199 while 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 # Put into this end stream object s2 = _get_another_stream (num) #获取另一端流对象 _xstream (NUM, conn, s2) If __name__ = ' __main__ ': If Len (SYS.ARGV)! = 3: _usage () sys.exit (1) tlist = [] # thread list, final deposit of two thread objects targv = [sys.argv[1], sys.argv[2]] for i in [0, 1]: s = Targ V[i] # stream describes 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: Host: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 the site.

I hope this article will help you with your Python programming.

Related Article

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.