python实现简单的实现简单的TCP代理服务器代理服务器
本文实例讲述了python实现简单的TCP代理服务器的方法,分享给大家供大家参考。
具体实现代码如下:
# -*- coding: utf-8 -*-
'''
filename:rtcp.py
@desc:
利用python的socket端口转发,用于远程维护
如果连接不到远程,会sleep 36s,最多尝试200(即两小时)
@usage:
./rtcp.py stream1 stream2
stream为:l:port或c:host:port
l:port表示监听指定的本地端口
c:host: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] # 存放需要进行数据转发的两个数据流(都是SocketObj对象)
debug = 1 # 调试状态 0 or 1
def _usage():
print 'Usage: ./rtcp.py stream1 stream2stream : l:port or c:host:port'
def _get_another_stream(num):
'''
从streams获取另外一个流对象,如果当前为空,则等待
'''
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):
'''
交换两个流的数据
num为当前流编号,主要用于调试目的,区分两个回路状态用。
'''
try:
while True:
#注意,recv函数会阻塞,直到对端完全关闭(close后还需要一定时间才能关闭,最快关闭方法是shutdow)
buff = s1.recv(1024)
if debug > 0:
print num,"recv"
if len(buff) == 0: #对端关闭连接,读不到数据
print num,"one closed"
评论0