python實(shí)現(xiàn)端口轉(zhuǎn)發(fā)器的方法
本文實(shí)例講述了python實(shí)現(xiàn)端口轉(zhuǎn)發(fā)器的方法。分享給大家供大家參考。具體如下:
下面的python代碼實(shí)現(xiàn)端口轉(zhuǎn)發(fā)器,支持udp端口轉(zhuǎn)發(fā)
由于工作需要用到一個(gè)端口轉(zhuǎn)發(fā)器,并且要求支持TCP和UDP協(xié)議。在網(wǎng)上找了蠻久,但沒(méi)有中意的。于是就自己寫(xiě)了一個(gè)。這個(gè)轉(zhuǎn)發(fā)器是基于python cookbook的一個(gè)示例改寫(xiě)的,原先的這個(gè)示例只支持TCP協(xié)議,我這里增加了UDP協(xié)議的支持,程序?qū)懙牟辉趺春?,不過(guò)它確實(shí)能用!
portmap.py代碼如下:
'''
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
self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.sock.bind((self.local_ip,port))
self.sock.listen(5)
log("start listen protocol:%s,port:%d " % ('tcp',port))
def run(self):
while True:
fwd=None
newsock=None
newsock,address=self.sock.accept()
log("new connection->protocol:%s,local port:%d,remote address:%s" % ('tcp',self.port,address[0]))
fwd=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
fwd.connect((self.newhost,self.newport))
except Exception ,ex:
log("connet newhost error:"+str(ex))
break
p1=pipethread(newsock,fwd,self.protocol)
p1.start()
p2=pipethread(fwd,newsock,self.protocol)
p2.start()
class pipethreadUDP(threading.Thread):
def __init__(self,connection,connectionTable,table_lock):
threading.Thread.__init__(self)
self.connection=connection
self.connectionTable=connectionTable
self.table_lock=table_lock
log('new thread for new connction')
def run(self):
while True:
try:
data,addr=self.connection['socket'].recvfrom(4096)
#log('recv from addr"%s' % str(addr))
except Exception ,ex:
log("recvfrom error:"+str(ex))
break
try:
self.connection['lock'].acquire()
self.connection['Serversocket'].sendto(data,self.connection['address'])
#log('sendto address:%s' % str(self.connection['address']))
except Exception ,ex:
log("sendto error:"+str(ex))
break
finally:self.connection['lock'].release()
self.connection['time']=time.time()
self.connection['socket'].close()
log("thread exit for: %s" % str(self.connection['address']))
self.table_lock.acquire()
self.connectionTable.pop(self.connection['address'])
self.table_lock.release()
log('Release udp connection for timeout:%s' % str(self.connection['address']))
class portmapUDP(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=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.sock.bind((self.local_ip,port))
self.connetcTable={}
self.port_lock=threading.Lock()
self.table_lock=threading.Lock()
self.timeout=300
#ScanUDP(self.connetcTable,self.table_lock).start()
log('udp port redirect run->local_ip:%s,local_port:%d,remote_ip:%s,remote_port:%d' % (local_ip,port,newhost,newport))
def run(self):
while True:
data,addr=self.sock.recvfrom(4096)
connection=None
newsock=None
self.table_lock.acquire()
connection=self.connetcTable.get(addr)
newconn=False
if connection is None:
connection={}
connection['address']=addr
newsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
newsock.settimeout(self.timeout)
connection['socket']=newsock
connection['lock']=self.port_lock
connection['Serversocket']=self.sock
connection['time']=time.time()
newconn=True
log('new connection:%s' % str(addr))
self.table_lock.release()
try:
connection['socket'].sendto(data,(self.newhost,self.newport))
except Exception ,ex:
log("sendto error:"+str(ex))
#break
if newconn:
self.connetcTable[addr]=connection
t1=pipethreadUDP(connection,self.connetcTable,self.table_lock)
t1.start()
log('main thread exit')
for key in self.connetcTable.keys():
self.connetcTable[key]['socket'].close()
if __name__=='__main__':
myp=portmapUDP(10061,'10.0.1.29',161)
myp.start()
#myp.__stop()
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python實(shí)現(xiàn)二叉搜索樹(shù)增刪改查
二叉搜索樹(shù)是一種特殊的二叉樹(shù),在本文中,我將介紹如何用Python語(yǔ)言實(shí)現(xiàn)一個(gè)簡(jiǎn)單的二叉搜索樹(shù),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2023-08-08
Python數(shù)據(jù)結(jié)構(gòu)與算法之常見(jiàn)的分配排序法示例【桶排序與基數(shù)排序】
這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)與算法之常見(jiàn)的分配排序法,結(jié)合實(shí)例形式分析了桶排序與基數(shù)排序的相關(guān)原理及實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-12-12
Python跳出循環(huán)語(yǔ)句continue與break的區(qū)別
這篇文章主要介紹了Python跳出循環(huán)語(yǔ)句continue與break的區(qū)別,本文用實(shí)例來(lái)說(shuō)明它們之間的區(qū)別,簡(jiǎn)單易記易懂,需要的朋友可以參考下2014-08-08
淺談Python數(shù)學(xué)建模之固定費(fèi)用問(wèn)題
本文主要介紹了Python固定費(fèi)用問(wèn)題的建模與求解。學(xué)習(xí) PuLP工具包中處理復(fù)雜問(wèn)題的快捷使用方式2021-06-06
淺談Python實(shí)現(xiàn)Apriori算法介紹
這篇文章主要介紹了淺談Python實(shí)現(xiàn)Apriori算法介紹,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12
Python+MySQL隨機(jī)試卷及答案生成程序的示例代碼
這篇文章主要介紹了Python+MySQL隨機(jī)試卷及答案生成程序的示例代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02

