Skip to content

Instantly share code, notes, and snippets.

@MayankFawkes
Last active October 19, 2020 08:55
Show Gist options
  • Select an option

  • Save MayankFawkes/ea692faec7efecda19d2507742feca83 to your computer and use it in GitHub Desktop.

Select an option

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
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