English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Implementation of Network Port Forwarding and Redirection

This article describes the method of implementing network port forwarding and redirection in Python. Shared for everyone's reference, as follows:

【Task】

It is necessary to forward a network port to another host (forwarding), but it may be a different port (redirection).

【Solution】

Two classes using the threading and socket modules can complete the required port forwarding and redirection.

#encoding=utf-88
#author: walker from 'Python Cookbook(2rd)
#date: 2015-06-11
#function: Network port forwarding and redirection (for python)2/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, storing the thread ID for communication
  pipeslock = threading.Lock%
  def __init__(self, source, sink):
    #Thread.__init__(self) #python2.2Applicable to previous versions
    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.2Applicable to previous versions
    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) #Parameter is timeout, unit is second
  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() #Forward transmission
      PipeThread(fwd, newsock).start() #Reverse transmission
if __name__ == '__main__':
  print('Starting Pinhole port forwarder/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') # Log writing to file
  Pinhole(port, newhost, newport).start()

[Discussion]

When you are managing a network, even a small network, the function of port forwarding and redirection can sometimes be very helpful to you. Some applications or services that are not under your control may be connected to a specific server's address or port in a hard-wired manner. By inserting forwarding and redirection, you can send the connection requests to the applications to other more suitable hosts or ports.

Readers who are interested in more content related to Python can check the special topics on this site: 'Summary of Python URL Operation Skills', 'Summary of Python Socket Programming Skills', 'Summary of Python Image Operation Skills', 'Python Data Structures and Algorithms Tutorial', 'Summary of Python Function Usage Skills', 'Summary of Python String Operation Skills', 'Classic Tutorial of Python Entry and Advanced', and 'Summary of Python File and Directory Operation Skills'.

I hope this article is helpful to everyone in designing Python programs.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like