本文實例講述了python實現端口轉發器的方法。分享給大家供大家參考。具體如下:
下面的python代碼實現端口轉發器,支持udp端口轉發
由于工作需要用到一個端口轉發器,并且要求支持TCP和UDP協議。在網上找了蠻久,但沒有中意的。于是就自己寫了一個。這個轉發器是基于python cookbook的一個示例改寫的,原先的這個示例只支持TCP協議,我這里增加了UDP協議的支持,程序寫的不怎么好,不過它確實能用!
portmap.py代碼如下:
代碼如下:#-* -coding: UTF-8 -* -
'''
Created on 2012-5-8
@author: qh
'''
import time,socket,threading
def log(strLog):
strs=time.strftime("%Y-%m-%d %H:%M:%S")
print strs+"->"+strLog
class pipethread(threading.Thread):
'''
classdocs
'''
def __init__(self,source,sink):
'''
Constructor
'''
threading.Thread.__init__(self)
self.source=source
self.sink=sink
log("New Pipe create:%s->%s" % (self.source.getpeername(),self.sink.getpeername()))
def run(self):
while True:
try:
data=self.source.recv(1024)
if not data: break
self.sink.send(data)
except Exception ,ex:
log("redirect error:"+str(ex))
break
self.source.close()
self.sink.close()
class portmap(threading.Thread):
def __init__(self,port,newhost,newport,local_ip=''):
threading.Thread.__init__(self)
self.newhost=newhost
self.newport=newport
self.port=port
self.local_ip=local_ip
self.sock=None
新聞熱點
疑難解答