SSH Access using Renci.SSH to MySQL Server

2019-07-23 11:01发布

Trying to access a MySQL server using the Renci host SSH library.

I got it working by following the info Creating a forwarded port within an SSH tunnel

Specifically this line got my local port sucessfully set up such that it could be bound:

ForwardedPortLocal port = new ForwardedPortLocal("localhost", 3306, "localhost", 3306));

This is fine, but as I understand it the SSH client is binding to 3306 to receive data back from the server. This is a problem if the user has MySQL already installed as it will be using this port so my service cannot. Of course the service can be stopped but this is not a very friendly process. I was expecting to be able to pass a High - Ephemeral - Port to listen on for the duration of my connection.

I got a bit confused on which parameter I should pass, having originally thought the second port would be the local port I need to bind to. After extensive experimentation on port configs I am at a loss as to how to handle this.

In addition I tried various overloads but none of the 3 other overloads seemed to produce what I wanted.

Any tips?

Thanks,

Andy

标签: c# mysql ssh
1条回答
地球回转人心会变
2楼-- · 2019-07-23 11:57

Ok I've resolved this now.

The solution is to modify the MySQL connector string so it uses a Ephemeral port. Picked one at random.

server=localhost; uid=;pwd=; database=; port=14324

Then modify the ForwardedLocalPort to bind to this port.

ForwardedPortLocal port = new ForwardedPortLocal("localhost", 14324, "localhost", 3306);

So we're forwarding the connection to localhost 14324 to localhost 3306 on the remote server.

Next challenge how to ensure that the port I use isn't already bound!!

So to do this use the overload that does not require a port number i.e.

ForwardedPortLocal("localhost", "localhost", 3306)

This will allocate an available Ephemeral port to your process which can be found using:

port.Start();
var portNumber = port.BoundPort;

This can then be added to your MySQL connection string.

查看更多
登录 后发表回答