import socket
import subprocess
import shlex

# SSH Local tunnel
# Authenticate to remote host, create tunnel, then login to the listening port using sockets
remote_host = "10.0.3.3"
username = "dylan"
local_port = 22
remote_port = 2222

cmd = "ssh -NT -L {}:localhost:{} {}@{}".format(remote_port, local_port, username, remote_host)

# Create tunnel to remote server, use Popen to keep process running in background
tunnel = subprocess.Popen(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
print("Tunnel opened!")

# Connect to tunnel we just created via Sockets
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", remote_port))
while True:
    try:
        response = s.recv(4096)
        if not response:
            break
        print(response.decode("utf-8"))
    except ConnectionRefusedError as err:
        print(err)
s.close()
tunnel.kill()
tunnel.terminate()
