python-3.xsshparamikossh-tunnelinternet-connection

How to send get request from remote host using ssh connection in python?


I'm using ssh connection with paramiko. My code:

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=remote_host, username=remote_user, password=remote_password, port=remote_port)

As I understand, if there are no exception: successfully connected. But how to send get request from connected remote host (use it like a proxy)?


Solution

  • There are two options:

    External tool

    Use any tool available on the SSH server that can send the HTTP request. E.g. curl or wget:

    curl https://www.example.com/
    

    And execute it using Paramiko: Python Paramiko - Run command

    This solution is easier, but has the dependency on the command – So it's also platform dependent.

    Port forwarding

    Forward a local port to the remote HTTP server port 80 and connect to the forwarded port using your local Python code.

    You will find lot of examples how to forward a database port.
    Like this one: Enable Python to Connect to MySQL via SSH Tunnelling

    In your case, you need to do the same, just instead of using a database client to connect to the forwarded port, you connect an HTTP client (like HTTPConnection).

    Also in most cases, the database forwarding usually ends on the SSH server itself (localhost/127.0.0.1), while you want to connect further.

    This solution is more complicated, but without external dependencies – So it's platform independent. On the other hand, the port forwarding is a special privilege, that may be restricted on the server (but usually it is not). Before trying to implement it, you can test it with your SSH client.