Python implements methods of network port forwarding and redirection

  • 2020-05-12 02:48:44
  • OfStack

This article illustrates how Python implements network port forwarding and redirection. I will share it with you for your reference as follows:

"Task"

A network port needs to be forwarded to another host (forwarding), but it may be a different port (redirecting).

[solution]

Two classes that use the threading and socket modules will do the port forwarding and redirection we need.


#encoding=utf8
#author: walker " Python Cookbook ( 2rd )" 
#date: 2015-06-11
#function:  Network port forwarding and redirection (applicable to python2/python3 ) 
import sys, socket, time, threading
LOGGING = True
loglock = threading.Lock()
# Print log to standard output 
def log(s, *a):
  if LOGGING:
    loglock.acquire()
    try:
      print('%s:%s' % (time.ctime(), (s % a)))
      sys.stdout.flush()
    finally:
      loglock.release()
class PipeThread(threading.Thread):
  pipes = []   # Static member variable that stores the thread number of the communication 
  pipeslock = threading.Lock()
  def __init__(self, source, sink):
    #Thread.__init__(self) #python2.2 Previous version applicable 
    super(PipeThread, self).__init__()
    self.source = source
    self.sink = sink
    log('Creating new pipe thread %s (%s -> %s)',
        self, source.getpeername(), sink.getpeername())
    self.pipeslock.acquire()
    try:
      self.pipes.append(self)
    finally:
      self.pipeslock.release()
    self.pipeslock.acquire()
    try:
      pipes_now = len(self.pipes)
    finally:
      self.pipeslock.release()
    log('%s pipes now active', pipes_now)
  def run(self):
    while True:
      try:
        data = self.source.recv(1024)
        if not data:
          break
        self.sink.send(data)
      except:
        break
    log('%s terminating', self)
    self.pipeslock.acquire()
    try:
      self.pipes.remove(self)
    finally:
      self.pipeslock.release()
    self.pipeslock.acquire()
    try:
      pipes_left = len(self.pipes)
    finally:
      self.pipeslock.release()
    log('%s pipes still active', pipes_left)
class Pinhole(threading.Thread):
  def __init__(self, port, newhost, newport):
    #Thread.__init__(self) #python2.2 Previous version applicable 
    super(Pinhole, self).__init__()
    log('Redirecting: localhost: %s->%s:%s', port, newhost, newport)
    self.newhost = newhost
    self.newport = newport
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.sock.bind(('', port))
    self.sock.listen(5) # Parameters for timeout , in seconds 
  def run(self):
    while True:
      newsock, address = self.sock.accept()
      log('Creating new session for %s:%s', *address)
      fwd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      fwd.connect((self.newhost, self.newport))
      PipeThread(newsock, fwd).start() # Positive transfer 
      PipeThread(fwd, newsock).start() # The reverse transmission 
if __name__ == '__main__':
  print('Starting Pinhole port fowarder/redirector')
  try:
    port = int(sys.argv[1])
    newhost = sys.argv[2]
    try:
      newport = int(sys.argv[3])
    except IndexError:
      newport = port
  except (ValueError, IndexError):
    print('Usage: %s port newhost [newport]' % sys.argv[0])
    sys.exit(1)
  #sys.stdout = open('pinhole.log', 'w') # Write the log to a file 
  Pinhole(port, newhost, newport).start()

[conversation]

When you're managing a network, even a small one, port forwarding and redirection can sometimes be a big help. Applications or services that are not under your control may be hardwired to the address or port of a particular server. By inserting forwards and redirects, you can send connection requests to applications to other hosts or ports that are more appropriate.

More about Python related topics: interested readers to view this site "Python URL skills summary", "Python Socket programming skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful for you to design Python program.


Related articles: