Boa*_*rdy 5 c++ mysql sockets ssh
我正在开发一个测试应用程序,以了解如何使用SSH隧道连接到C++中的MySQL数据库.
我正在使用libssh2库,我正在使用https://www.libssh2.org/examples/direct_tcpip.html中的示例,但我不能100%确定这是否正确使用.
我几乎复制了这个例子但是当我在socket上连接到MySQL时,MySQL会抛出:
Errro 2013(HY000):在"读取通信包"时丢失了与mysql服务器的连接,系统错误:0
当我使用mysql -uroot -p -P2222连接到mysql时,我的应用程序使用以下内容读取通道上的数据:
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;
}
Run Code Online (Sandbox Code Playgroud)
发送完成后,我立即得到mysql错误.我认为这是因为我发送SSH-2.0- MySQL 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;
Run Code Online (Sandbox Code Playgroud)
由于示例中的remote_destport 为22,我认为这是SSH 连接详细信息,因此我将其设置为我的SSH 设置。
事实证明这是连接从 SSH 会话转发到的地方,所以我将其更改为
const char *remote_desthost = "localhost"; /* resolved by the server */
unsigned int remote_destport = 3306;
Run Code Online (Sandbox Code Playgroud)
现在我可以从我的笔记本电脑运行我的应用程序,它连接到我的 Web 服务器的 SSH 服务器,然后在我的笔记本电脑上运行命令
mysql -uroot -p -P2222我通过 SSH 隧道连接到网络服务器上的数据库。