Last active
October 19, 2020 08:55
-
-
Save MayankFawkes/ea692faec7efecda19d2507742feca83 to your computer and use it in GitHub Desktop.
Redirect traffic from one port to another | Example Transfer traffic from 127.0.0.1:5000 to 127.0.0.1:9050 | Port forwarding with Python3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import socket, sys, signal | |
| import select, threading | |
| signal.signal(signal.SIGINT, lambda a,b: exec('print(f"[+]Socket server shutting down ...")\nsys.exit(0)')) | |
| class Server: | |
| def __init__(self,lhost:tuple,rhost:tuple,debug=True): | |
| self.lhost = lhost | |
| self.rhost = rhost | |
| self.debug = debug | |
| self._connect() | |
| def _connect(self): | |
| if self.debug:print(f"[+]Connecting socket") | |
| self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) | |
| self.sock.bind(self.lhost) | |
| if self.debug:print(f"[+]Socket Listening at {self.lhost[0]}:{self.lhost[1]}") | |
| self.sock.listen(5) | |
| self._accept() | |
| def _accept(self): | |
| while True: | |
| conn, address =self.sock.accept() | |
| threading.Thread(target=self._worker,args=(conn,address)).start() | |
| def _worker(self, conn, address): | |
| tempSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) | |
| tempSock.connect(self.rhost) | |
| if self.debug:print(f"[+]Socket recv data from {address[0]}:{address[1]}") | |
| while True: | |
| triple=select.select([tempSock,conn],[],[],2)[0] | |
| if not len(triple):break | |
| if conn in triple: | |
| what=conn.recv(5120) | |
| if not what:break | |
| tempSock.send(what) | |
| if tempSock in triple: | |
| what=tempSock.recv(5120) | |
| if not what:break | |
| conn.send(what) | |
| if self.debug:print(f"[+]Socket connection closed {address[0]}:{address[1]}") | |
| conn.close() | |
| if __name__ == '__main__': | |
| lhost=("0.0.0.0",5000) # Local Host and Port | |
| rhost=("0.0.0.0",9050) # remote Host and Port | |
| Server(lhost,rhost) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment