【发布时间】:2016-05-02 23:55:35
【问题描述】:
我已尽一切努力创建与远程 MySQL 数据库的 SSH 连接。
String user = "user";
String password = "pass";
String remoteHost = "host";
int localPort = 2022;
int remotePort = 3306;
Session session = null;
//Try to forward ports
try
{
//Create the JSCH object
JSch jsch = new JSch();
//Get the session
session = jsch.getSession(user, remoteHost);
//Set the password
session.setPassword(password);
//To be able to connect to any host (this is just for testing!)
session.setConfig("StrictHostKeyChecking", "no");
//Connect the session
session.connect();
//Set port forward
session.setPortForwardingL(localPort, "127.0.0.1", remotePort);
//Show message
System.out.println("Waiting for connections…");
//Exit on return
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
in.readLine();
}
//Failed
catch(Exception ex)
{
//Message
System.out.println("Failed to setup tunnel");
//Stack trace
ex.printStackTrace();
}
//Clean up
finally
{
try{session.disconnect();} catch(Throwable t) {t.printStackTrace();}
}
但我不断收到此错误:com.jcraft.jsch.JSchException: java.net.ConnectException: Operation timed out
我不明白为什么它会给我这个错误,因为我相信我使用了正确的信息。所以我的问题是,我将如何检查主机的远程 ip,以及如何确保它们确实允许 SSH 访问?
更新:
我可以通过 ssh -v user@host 连接到远程 MySQL 数据库。但是,在我的代码中,我收到了这个错误:
com.jcraft.jsch.JSchException: PortForwardingL: 本地端口 127.0.0.1:2022 无法绑定。
我用的是mac,mac的本地端口是不是不一样?
【问题讨论】:
-
您可能应该指定 ssh 端口 (
int remotePort = 22;);如果这不起作用,您需要询问您的提供商。 -
端口
3306用于mysql。你想用 ssh 做什么?只有通过 ssh 的远程 ssh 或 mysql 连接?? -
能否请您发布异常的 statcktrace ?如果您的手动连接正常,包括 MySQL 端口的转发。那么你的代码也应该可以工作。因为到目前为止没有任何问题。
-
我得到的异常是:com.jcraft.jsch.JSchException: PortForwardingL: local port 127.0.0.1:2022 cannot be bound。
-
local port 127.0.0.1:2022 cannot be bound表示端口2022已在您的本地计算机上使用。也许你有这个会话ssh -v user@host -L 2022:127.0.0.1:3306仍然开放?