Python implements a simple TCP proxy server
- 2020-04-02 14:15:42
- OfStack
This article illustrates the python implementation of a simple TCP proxy server method, to share with you for your reference.
The specific implementation code is as follows:
# -*- coding: utf-8 -*-
'''
filename:rtcp.py
@desc:
using python the socket Port forwarding for remote maintenance
If you can't connect remotely, yes sleep 36s At most 200( In two hours )
@usage:
./rtcp.py stream1 stream2
stream To: l:port or c:host:port
l:port Represents listening on the specified local port
c:host:port Represents listening on a remotely specified port
@author: watercloud, zd, knownsec team
@web: www.knownsec.com, blog.knownsec.com
@date: 2009-7
'''
import socket
import sys
import threading
import time
streams = [None, None] # Holds two data streams (both) that require data forwarding SocketObj Object)
debug = 1 # Debug state 0 or 1
def _usage():
print 'Usage: ./rtcp.py stream1 stream2nstream : l:port or c:host:port'
def _get_another_stream(num):
'''
from streams Gets another stream object and waits if it is currently empty
'''
if num == 0:
num = 1
elif num == 1:
num = 0
else:
raise "ERROR"
while True:
if streams[num] == 'quit':
print("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):
'''
Exchange data from two streams
num Number the current stream , It is mainly used for debugging purposes to distinguish the two loop states.
'''
try:
while True:
# Pay attention to, recv The function blocks until the opposite is completely closed ( close After also need some time to close, the fastest way to close is shutdow )
buff = s1.recv(1024)
if debug > 0:
print num,"recv"
if len(buff) == 0: # The opposite end closes the connection and the data cannot be read
print num,"one closed"
break
s2.sendall(buff)
if debug > 0:
print 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):
'''
Handling service status ,num Is the stream number (no 0 Size or the first. 1 ) no.
'''
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 # Place the endstream object
s2 = _get_another_stream(num) # Gets the other end stream object
_xstream(num, conn, s2)
def _connect(host, port, num):
''' Handle connections, num Is the stream number (no 0 Size or the first. 1 ) no.
@note: If you can't connect remotely, yes sleep 36s At most 200( In two hours )
'''
not_connet_time = 0
wait_time = 36
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 # Place the endstream object
s2 = _get_another_stream(num) # Gets the other end stream object
_xstream(num, conn, s2)
if __name__ == '__main__':
if len(sys.argv) != 3:
_usage()
sys.exit(1)
tlist = [] # A list of threads that eventually hold two thread objects
targv = [sys.argv[1], sys.argv[2] ]
for i in [0, 1]:
s = targv[i] # stream describe 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)
Complete sample code click here (link: http://xiazai.jb51.net/201410/yuanma/python-rtcp-master (jb51.net). Rar).
I hope this article has helped you with your Python programming.