This article illustrates how Python implements network port forwarding and redirection. Share to everyone for your reference, specific as follows:
Task
A network port needs to be forwarded to another host (forwarding), but may be a different port (redirecting).
"Solution"
Two classes that use the threading and socket modules will be able to complete the port forwarding and redirection we need.
#encoding =utf8 #author: Walker excerpt from The Python Cookbook (2rd) #date: 2015-06-11 #function: Forwarding and redirection of network ports (for Python2/python3) Import sys, socket, time, threading LOGGING = True Loglock = Threading. Lock () #打印日志到标准输出 def log (S, *a): If LOGGING:loglock.acquire () try:print ('%s:%s '% (Time.ctime (), (s) )) Sys.stdout.flush () finally:loglock.release () class Pipethread () (threading. Thread): pipes = [] #静态成员变量, the number Pipeslock = threading that stores the traffic. Lock () def __init__ (self, source, sink): #Thread. __init__ (self) before #python2.2 The version applies to super (Pipethread, self). __init_ _ () Self.source = Source Self.sink = Sink log (' Creating new pipe thread%s (%s->%s) ', Self, SOURC
E.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 nowActive ', 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.pipeslo Ck.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) before #python2.2 The version applies to super (pinhole, self ). __init__ () log (' Redirecting:localhost:%s->%s:%s ', Port, Newhost, Newport) Self.newhost = Newhost SELF.N Ewport = Newport Self.sock = socket.socket (socket.af_inet, socket.
Sock_stream) Self.sock.bind ((', Port) Self.sock.listen (5) #参数为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 () #正向传送 Pipethread (Fwd, Newsock). Start () #逆向传送 If __name__ = ' __main__ ': print (' Starting pinhole port Fowarder/redirector ') Try:po RT = Int (sys.argv[1]) Newhost = sys.argv[2] try:newport = Int (sys.argv[3)) except Indexerror:new
Port = port except (ValueError, Indexerror): Print (' Usage:%s port newhost [Newport] '% sys.argv[0]) sys.exit (1)
#sys. StdOut = open (' Pinhole.log ', ' W ') #将日志写入文件 pinhole (port, Newhost, Newport). Start ()
Discussion
When you are managing a network, even a very small network, port forwarding and redirection of the function can also give you a lot of help. Some applications or services that are not under your control may be connected to a particular server's address or port in a hard-wired manner. By inserting forwarding and redirection, you can send a connection request to an application to a more appropriate host or port.
More information about Python-related content can be viewed in this site: "Python URL Operation tips Summary", "Python Socket Programming Tips Summary", "Python Picture Operation skills Summary", "Python data structure and Algorithms tutorial", " Python function Usage Tips Summary, python string manipulation tips, Python introductory and Advanced classic tutorials, and Python file and directory how-to tips
I hope this article will help you with Python programming.