pythonsshlocalhostssh-tunnel

how to serve an API at localhost and access it from ssh


I have zero experience in this.

I'm trying to create a API in my local machine, and call that API from the SSH

server.py:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/", methods=["GET"])

def get_info():
    return jsonify({"data": "hi"})
    # from openai import OpenAI


if __name__ == "__main__":
    app.run(debug=True)

and this is client.py on SSH machine.

Edit: I mean. the server.py is created on local host. and client.py (another project) is created on SSH (as I understand is remote machine). Though both are created using my machine.

import requests
import json
import socket
# request = b"GET / HTTP/1.1\nHost: www.cnn.com\n\n"
s = socket.socket()
s.connect(("127.0.0.1",5000))
s.sendall(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")
print(s.recv(1024))

url = 'http://localhost:5000'

response = requests.get(url)
print(response)

# print(str(response))
# print('')
# print(json.dumps(response.json(), indent=4))

Sorry I don't understand any at all about the socket I just follow some code on the internet but it doesn't work.

Thank you.

Edit: when run client.py on SSH. I received error result


b'HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\nDate: Mon, 16 Sep 2024 08:44:33 GMT\r\nServer: Warp/3.3.17\r\n\r\n0\r\n\r\n'
<Response [404]>

I also followed this. but doesn't work:

Option 2: Use SSH Tunneling (Port Forwarding)

If the local API is bound to localhost and you don’t want to expose it publicly, SSH tunneling is a more secure option.

2.1 Keep the API Bound to localhost

Start the API normally on your local machine, keeping it bound to localhost. For example:

flask run --host=127.0.0.1 --port=5000
ssh -L 4032:localhost:5000 nld@103.119.132.170
curl http://localhost:5000

Test (stand on remote machine):

import requests
requests.get("http://127.0.0.1:4032")

-> <Response [404]>

import requests
requests.get("http://localhost:4032")

-> <Response [404]>

import requests
requests.get("http://localhost:5000")

-> <Response [404]>

Solution

  • Okay, I already figured out. Turn out I was standing on a wrong side to call tunnel.

    I have to stand on local machine and run

    ssh -R 8080:localhost:5000 user@remote_server

    https://www.ssh.com/academy/ssh/tunneling-example