Python implements network port forwarding and redirection, and python redirection
This article describes how to implement network port forwarding and redirection in Python. We will share this with you for your reference. The details are as follows:
[Task]
You need to forward a network port to another host (forwarding), but it may be a different port (redirecting ).
[Solution]
Two classes using threading and socket modules can complete the port forwarding and redirection we need.
# Encoding = utf8 # author: walker is taken from Python Cookbook (2rd) # date: 2015-06-11 # function: Forward and redirect network ports (applicable to python2/python3) import sys, socket, time, threadingLOGGING = Trueloglock = threading. lock () # print the log to the 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. The Thread number for storing communication is pipeslock = threading. lock () def _ init _ (self, source, sink): # Thread. _ init _ (self) # versions earlier than python2.2 are applicable to 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) failed T: 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) # versions earlier than python2.2 are applicable to 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) # The parameter is timeout. The 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 transfer PipeThread (fwd, newsock ). start () # reverse transfer 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]) handle T IndexError: newport = port handle T (ValueError, IndexError): print ('usage: % s port newhost [newport] '% sys. argv [0]) sys. exit (1) # sys. stdout = open ('pinhole. log', 'w') # Write the log into the file Pinhole (port, newhost, newport ). start ()
[Discussion]
When you are managing a network, even a small network, the port forwarding and redirection functions can sometimes help you a lot. Some applications or services that are not under your control may be connected to the IP address or port of a specific server through hard connection. By inserting forwarding and redirection, you can send application connection requests to other more suitable hosts or ports.