我正在开发一个测试应用程序,以了解如何使用 SSH 隧道连接到 C++ 中的 MySQL 数据库。
我正在使用 libssh2 库,我正在使用来自 https://www.libssh2.org/examples/direct_tcpip.html 的示例但我不是 100% 确定这是否是正确的使用方法。
我几乎复制了这个例子,但是当在我的套接字上连接到 MySQL 时,MySQL 抛出:
Errro 2013 (HY000): Lost connection to mysql server at 'reading communication packet', system error: 0
当我使用 mysql -uroot -p -P2222 连接到 mysql 时,我的应用程序使用以下命令读取 channel 上的数据:
int len = libssh2_channel_read(channel, buf, sizeof(len));
并且 buf 包含 SSH-2.0-
然后将其写入转发套接字,如下所示:
wr = 0;
while (wr < len)
{
i = send(forward_socket, buf + wr, len - wr, 0);
if (i <= 0)
{
perror("write");
return EXIT_FAILURE;
}
wr += i;
}
发送完成后,我立即收到 mysql 错误。我认为这是因为我正在向 MySQL 发送 SSH-2.0- MySQL 不希望它关闭连接但我看不出有什么问题,而且我无法确定 libssh2 direct_tcpip 是否正确要使用的东西。
最佳答案
最后,经过大量的反复试验,设法弄清楚该怎么做。
使用 https://www.libssh2.org/examples/direct_tcpip.html 中的示例但是我用错误的值设置了变量。
基本上,在示例中它有
const char *remote_desthost = "localhost"; /* resolved by the server */
unsigned int remote_destport = 22;
因为示例中的 remote_destport 为 22,我认为这是 SSH 连接详细信息,所以我将其设置为我的 SSH 设置。
事实证明这是连接从 SSH session 转发到的地方,所以我将其更改为
const char *remote_desthost = "localhost"; /* resolved by the server */
unsigned int remote_destport = 3306;
现在我可以从我的笔记本电脑上运行我的应用程序,它连接到我的 Web 服务器的 SSH 服务器,然后在我的笔记本电脑上运行命令
mysql -uroot -p -P2222
我通过 SSH 隧道连接到我的网络服务器上的数据库。
关于c++ - 在 C++ 中通过 SSH 隧道连接到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41170816/