如何通过SSH连接远程MS SQL服务器?问题排查求助
SSH隧道连接远程MS SQL的端口配置问题
我查了多个Stack Overflow问题,还是没法建立连接,对连接设置里的IP和端口配置完全搞不清。
我已经在远程路由器上配置了端口转发到Debian无头服务器,SSH服务器监听转发后的<remoteIP>。我能通过命令ssh userName@<remoteRouterIP> -p <remotePort>手动SSH连接到远程PC,连接后用sqlcmd -C -S localhost -U SA能正常连接MS SQL。
从Windows PC连接远程服务器时,client.Connect();显示成功,但报错The remote computer refused the network connection。是不是要把远程PC的MS SQL监听端口(1433)改成<remotePort>?
更新:根据评论修改了连接字符串,把端口改成路由器转发到PC的允许端口后,现在报错:
System.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake.
附上我的代码:
var privateKey = new PrivateKeyFile(@"C:\Users\...\.ssh\id_ed25519", "<passPhrase>"); var keyFiles = new[] { privateKey }; var methods = new List<AuthenticationMethod>(); methods.Add(new PrivateKeyAuthenticationMethod("<remotePCUserName>",keyFiles)); Debug.WriteLine("SSHTest begins:"); var connectionInfo = new ConnectionInfo("<remoteRouterIP>",<port>, "userName", methods.ToArray()); string sqlConnectionString = @"server=tcp:127.0.0.1, <remotePC_ForwardingPort>; Initial Catalog=<dbName>;Integrated Security=False;User ID=SA;Password=<password>; TrustServerCertificate=True"; using (var client = new SshClient(connectionInfo)) { try { client.Connect(); if(client.IsConnected) { Debug.WriteLine("SSH connection success: {0}", client.ConnectionInfo.ToString()); var portFWD = new ForwardedPortLocal("127.0.0.1",<remoteRouterPort>, "127.0.0.1", <remoteRouterPort>); client.AddForwardedPort(portFWD); portFWD.Start(); if(portFWD.IsStarted) { Debug.WriteLine("Port forwarded: {0}", portFWD.ToString()); DataTable dataTable = new DataTable(); try { using (SqlConnection connection = new SqlConnection(sqlConnectionString)) { using (SqlDataAdapter adaptor = new SqlDataAdapter("Select * from Table", sqlConnectionString)) { adaptor.Fill(dataTable); } } } catch (Exception ex) { Debug.WriteLine("Port forward FAIL: {0}", portFWD.ToString()); Debug.WriteLine(ex); } } } else { Debug.WriteLine("SSH connection failed: {0}", client.ConnectionInfo.ToString()); } } catch(Exception ex) { } }
请问远程PC需要设置让SSH把特定端口转发到MS SQL的监听端口吗?我以为代码里已经实现这个转发了,是不是哪里错了?
内容的提问来源于stack exchange,提问作者Allstar
相关产品推荐
相关产品推荐

