naheliegend
naheliegend

Reputation: 197

Python: SSH connection works with terminal but not in Python script

When I am using the Terminal with:

ssh user@ip-adress

and enter my password

ssh-password

then everything works fine and a connection gets established which I can close with exit.

But when I am trying to do that in Python:

import sshtunnel
from sshtunnel import SSHTunnelForwarder

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

server = SSHTunnelForwarder(
    'ip-adress', 22,
    ssh_username="user",
    ssh_password="ssh-password",
    remote_bind_address=('127.0.0.1', 3306)
)

server.start()

print(server.local_bind_port)

I'll receive an error like:

sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway

Why?

Upvotes: 1

Views: 3169

Answers (1)

YuTendo
YuTendo

Reputation: 339

There is actually a difference between your two examples. The first one just establishes a SSH connection where the Python code tries to establish a connection to a service on the remote machine which is listening on port 3306 (probably MySQL).

So for actually just establishing a SSH connection. I would refer you to Paramiko: http://www.paramiko.org/

(Cite: Paramiko is a Python (2.7, 3.4+) implementation of the SSHv2 protocol [1], providing both client and server functionality)

Using this library essentially allows the following:

ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)

Hence, you can execute any arbitrary command (assuming that you have the permission) -as you did in your first example.

However, when you really want to connect to a specific service (like MySQL). Then your second approach is fine and you should double check that your service is listening on 127.0.0.1:3306, e.g., with the following command:

netstat -tulpen

(This command needs to be executed on the remote machine.)

Upvotes: 1

Related Questions