需要安装python2.5以上及twisted开发包
程序中的参数配置的函意是:126邮箱的中转服务器
程序中的参数配置的函意是:126邮箱的中转服务器
- #!/usr/bin/env python
- # encoding: utf-8
- #
- # ################################################################
- #
- # 作者:黄江斌 (hjbcn@126.com)
- #
- # 版本:v1.0.0
- #
- # 来源:http://blog.csdn.net/zerodspace
- #
- # 工作模型
- #
- # 客户端 目标主机
- # ^ ^
- # | |
- # v v
- # 接收器 <--------> 转发器
- #
- # 映射表结构
- #
- # ( "客户端IP", 本地端口, "目标主机IP", 目标主机端口 )
- #
- # ################################################################
- from twisted.internet import protocol
- from twisted.internet import reactor
- TCPPortRedirectMap = [
- ( "*", 28, "smtp.126.com", 25 ),
- ( "*", 29, "pop.126.com", 110 ),
- ]
- class TCPPortRedirectorProtocol( protocol.Protocol ):
- def dataReceived( self, data ):
- # 所有接收到的数据都转发到“接收器”
- self.factory.recver.transport.write( data )
- print data
- def connectionLost( self, reason ):
- # 目标主机关闭连接后
- # 通知“接收器”关闭连接
- self.factory.recver.transport.loseConnection()
- class TCPPortRedirectorFactory( protocol.ClientFactory ):
- protocol = TCPPortRedirectorProtocol
- def __init__( self, recver ):
- # 保存“接收器”对象
- self.recver = recver
- self.connector = None
- def startedConnecting( self, connector ):
- # 保存“目标主机”与“转发器”的“连接对象”
- # 供外部使用
- self.connector = connector
- class TCPPortRedirectProtocol( protocol.Protocol ):
- def connectionMade( self ):
- # 获取连接信息
- #
- # 远程主机IP
- # 本地端口
- remote = self.transport.getPeer().host
- localhostPort = self.transport.getHost().port
- # 查找映射表
- # 确定转发目的地
- redirectMap = None
- for map in TCPPortRedirectMap:
- if ( map[0] == remote or map[0] == "*" ) and map[1] == localhostPort:
- redirectMap = map
- break
- # 如果没有找到转发关系
- # 关闭连接
- if not redirectMap:
- self.transport.loseConnection()
- # 建立转发器
- self.redirector = TCPPortRedirectorFactory( self )
- reactor.connectTCP( redirectMap[2], redirectMap[3], self.redirector )
- def dataReceived( self, data ):
- self.redirector.connector.transport.write( data )
- print data
- def connectionLost( self, reason ):
- self.redirector.connector.transport.loseConnection()
- class TCPPortRedirectFactory( protocol.Factory ):
- protocol = TCPPortRedirectProtocol
- def TCPPortRedirectStart():
- ports = []
- for map in TCPPortRedirectMap:
- if map[1] not in ports:
- ports.append( map[1] )
- for port in ports:
- reactor.listenTCP( port, TCPPortRedirectFactory() )
- reactor.run()
- if __name__ == "__main__":
- TCPPortRedirectStart()