Python methods for implementing port forwarders _python

Source: Internet
Author: User

The example in this article describes how Python implements a port forwarder. Share to everyone for your reference. Specifically as follows:

The following Python code implements a port forwarder that supports UDP port forwarding

A port forwarder is required for work and requires support for TCP and UDP protocols. Looking for a long time on the internet, but did not enjoy. So I wrote one for myself. This forwarder is based on an example of the Python cookbook, the original example only supports the TCP protocol, I have increased the support of the UDP protocol, the program does not write well, but it does work!

The portmap.py code is as follows:

Copy Code code as follows:
#-*-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
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 to 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 ()

I hope this article will help you with your Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.