使用Python的twisted和socket模块实现端口的负载分发

简介:

103109652.jpg

很简单的需求,自己写个类似iptables那样的dnat端口转发,简单实现像lvs那样的nat模式的端口的负载分发,当然性能堪忧哈~


这个例子是 监听 本地ip的9999端口,然后映射到另一个端口上,也可以利用random参数,进行多个端口的轮训,当然他的算法和性能简单,不能和lvs 相比了。


映射的版本:


执行方法:python th.py 8888 10.10.10.63 80


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python
#python th.py 8888 10.10.10.63 80
import  sys, socket, time, threading
loglock  =  threading.Lock()
def  log(msg):
loglock.acquire()
try :
print  '[%s]: \n%s\n'  %  (time.ctime(), msg.strip())
sys.stdout.flush()
finally :
loglock.release()
class  PipeThread(threading.Thread):
def  __init__( self , source, target):
threading.Thread.__init__( self )
self .source  =  source
self .target  =  target
def  run( self ):
while  True :
try :
data  =  self .source.recv( 1024 )
log(data)
if  not  data:  break
self .target.send(data)
except :
break
log( 'PipeThread done' )
class  Forwarding(threading.Thread):
def  __init__( self , port, targethost, targetport):
threading.Thread.__init__( self )
self .targethost  =  targethost
self .targetport  =  targetport
self .sock  =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self .sock.bind(( '0.0.0.0' , port))
self .sock.listen( 10 )
def  run( self ):
while  True :
client_fd, client_addr  =  self .sock.accept()
target_fd  =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target_fd.connect(( self .targethost,  self .targetport))
log( 'new connect' )
# two direct pipe
PipeThread(target_fd, client_fd).start()
PipeThread(client_fd, target_fd).start()
if  __name__  = =  '__main__' :
print  'Starting'
import  sys
try :
port  =  int (sys.argv[ 1 ])
targethost  =  sys.argv[ 2 ]
try : targetport  =  int (sys.argv[ 3 ])
except  IndexError: targetport  =  port
except  (ValueError, IndexError):
print  'Usage: %s port targethost [targetport]'  %  sys.argv[ 0 ]
sys.exit( 1 )
#sys.stdout = open('forwaring.log', 'w')
Forwarding(port, targethost, targetport).start()


附带负载的版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python
import  sys, socket, time, threading
loglock  =  threading.Lock()
def  log(msg):
loglock.acquire()
try :
print  '[%s]: \n%s\n'  %  (time.ctime(), msg.strip())
sys.stdout.flush()
finally :
loglock.release()
class  PipeThread(threading.Thread):
def  __init__( self , source, target):
threading.Thread.__init__( self )
self .source  =  source
self .target  =  target
def  run( self ):
while  True :
try :
data  =  self .source.recv( 1024 )
log(data)
if  not  data:  break
self .target.send(data)
except :
break
log( 'PipeThread done' )
class  Forwarding(threading.Thread):
def  __init__( self , port, targethost, targetport):
number  =  random.randint( 1 , 2 )
numbers  =  '%d'  % number
portlist = { '1' : 80 , '2' : 81 }
host = '10.10.10.63'
threading.Thread.__init__( self )
self .targethost  =  targethost
self .targetport  =  portlist[numbers]
self .sock  =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self .sock.bind(( '0.0.0.0' , port))
self .sock.listen( 10 )
def  run( self ):
while  True :
client_fd, client_addr  =  self .sock.accept()
target_fd  =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target_fd.connect(( self .targethost, portlist[numbers]))
log( 'new connect' )
# two direct pipe
PipeThread(target_fd, client_fd).start()
PipeThread(client_fd, target_fd).start()
if  __name__  = =  '__main__' :
print  'Starting'
import  sys
import  random
number  =  random.randint( 1 , 2 )
numbers  =  '%d'  % number
#sys.stdout = open('forwaring.log', 'w')
portlist = { '1' : 80 , '2' : 81 }
host = '10.10.10.63'
Forwarding( 9999 ,host, portlist[numbers]).start()


对于性能要求高的,可以试试twisted端口转发的代码。

调优方向  I/O模型,比如阻塞、非阻塞和反应式(select,poll,WaitForMultipleObject)


1
2
3
4
现在用gevent比较多,一是gevent性能会更好一些,而且用同步的方式来实现异步(使用greenlet),twisted中defer 和
callback 会把逻辑打散。
当初从twisted转到gevent最主要的原因是在twisted上很难实现多进程。
gevent不好的地方就是它的mongkey_patch 有时候会带来一些奇怪的问题。


个人感觉,twisted的优点是程序的各种设计,要是针对于咱们这个映射需求的话,推荐使用gevent网络并发框架。  这个也是我较常用的。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from twisted.internet.protocol  import  Protocol,ClientCreator
from twisted.internet  import  reactor
from twisted.protocols.basic  import  LineReceiver
from twisted.internet.protocol  import  Factory,ClientFactory
class  Transfer(Protocol):
def __init__(self):
pass
def connectionMade(self):
c = ClientCreator(reactor,Clienttransfer)
c.connectTCP( "10.10.10.63" , 80 ).addCallback(self.set_protocol)
self.transport.pauseProducing()
def set_protocol(self,p):
self.server = p
p.set_protocol(self)
def dataReceived(self,data):
self.server.transport.write(data)
def connectionLost(self,reason):
self.transport.loseConnection()
self.server.transport.loseConnection()
class  Clienttransfer(Protocol):
def __init__(self):
pass
def set_protocol(self,p):
self.server = p
self.server.transport.resumeProducing()
pass
def dataReceived(self,data):
self.server.transport.write(data)
pass
factory = Factory()
factory.protocol = Transfer
reactor.listenTCP( 9999 ,factory)
reactor.run()



完成 !





 本文转自 rfyiamcool 51CTO博客,原文链接:http://blog.51cto.com/rfyiamcool/1203660,如需转载请自行联系原作者


相关文章
|
24天前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
217 7
|
1月前
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
196 0
|
28天前
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
245 4
|
25天前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
194 0
|
26天前
|
XML JSON 数据处理
超越JSON:Python结构化数据处理模块全解析
本文深入解析Python中12个核心数据处理模块,涵盖csv、pandas、pickle、shelve、struct、configparser、xml、numpy、array、sqlite3和msgpack,覆盖表格处理、序列化、配置管理、科学计算等六大场景,结合真实案例与决策树,助你高效应对各类数据挑战。(238字)
137 0
|
2月前
|
安全 大数据 程序员
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
`operator.methodcaller`是Python中处理对象方法调用的高效工具,替代冗长Lambda,提升代码可读性与性能。适用于数据过滤、排序、转换等场景,支持参数传递与链式调用,是函数式编程的隐藏利器。
110 4
|
2月前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
243 0
|
2月前
|
网络协议
端口最多只有65535个,为什么服务器能承受百万并发
服务器通过四元组(源IP、源端口、目标IP、目标端口)识别不同TCP连接,每条连接对应独立socket。数据包携带四元组信息,服务端据此查找对应socket进行通信。只要四元组任一元素不同,即视为新连接,可创建独立socket。资源充足时,单进程可支持百万级并发连接,socket与端口非一一对应。
165 10
端口最多只有65535个,为什么服务器能承受百万并发
|
4月前
|
SQL Apache Windows
Windows服务器80端口被占用的全面解决方案
在服务管理器中启动apache2服务,即可正常使用80端口。若系统中还安装了其他微软产品如sql等,也可尝试停止其服务进行测试,但请注意,SQL通常不会使用80端口,因此一般不会受到影响。以上就是关于80端口被system占用的详细解决方法,希望对你有所帮助。
|
7月前
|
网络协议 安全 应用服务中间件
云服务器怎么开启被关闭的端口?手把手教你开启端口
在使用云服务器时,若发现某些服务无法访问,可能是端口被关闭。本文介绍了端口关闭的原因、检查方法及开启步骤。原因包括初始设置限制、防火墙规则和外部网络策略;可通过netstat或ss命令检查端口状态,用ufw、iptables或firewalld调整防火墙规则。最后提供了解决常见问题的建议,确保端口正常开放并可供外网访问。
1369 9

推荐镜像

更多