我的asp.net项目需要连接到mysql,我正在寻找配置数据库连接的解决方法,我看到打开3306很危险,准备使用ssh隧道来连接到数据库
出于安全原因,有时只能通过 SSH 访问数据库服务器。 比如MySql服务安装在服务器A上,机器A只能被机器B访问,而部署环境可能在机器C上,此时C服务器通过B服务器连接到A服务器。 此时需要SSH连接,需要SSH.NET类库:
代码如下:
using MySql.Data.MySqlClient;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SSHMySql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SSHConnectMySql();
}
public void SSHConnectMySql()
{
string SSHHost = "*.*.*.*"; // SSH address
int SSHPort = ; // SSH port
string SSHUser = "user"; // SSH username
string SSHPassword = "pwd"; // SSH password
string sqlIPA = "127.0.0.1";// Map addresses In fact, it is possible to write other MySql on Linux My.cnf bind-address can be set to 0.0.0.0 or not
string sqlHost = "192.168.1.20"; // The IP address of the machine installed by mysql can also be an intranet IP, for example: 192.168.1.20
uint sqlport = ; // Database port and mapping port
string sqlConn = "Database=mysql;Data Source=" + sqlIPA + ";Port=" + sqlport + ";User Id=user;Password=pwd;CharSet=utf8";
string sqlSELECT = "select * from user";
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(SSHHost, SSHPort, SSHUser, SSHPassword);
connectionInfo.Timeout = TimeSpan.FromSeconds();
using (var client = new SshClient(connectionInfo))
{
try
{
client.Connect();
if (!client.IsConnected)
{
MessageBox.Show("SSH connect failed");
}
var portFwdL = new ForwardedPortLocal(sqlIPA, sqlport, sqlHost, sqlport); // map to local port
client.AddForwardedPort(portFwdL);
portFwdL.Start();
if (!client.IsConnected)
{
MessageBox.Show("port forwarding failed");
}
MySqlConnection conn = new MySqlConnection(sqlConn);
MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
myDataAdapter.SelectCommand = new MySqlCommand(sqlSELECT, conn);
try
{
conn.Open();
DataSet ds = new DataSet();
myDataAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[];
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
conn.Close();
}
client.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
注意:如果出现错误,可以在本地(开发机)停止MySql服务。
所需dll:SSHDLL.rar
在 Visual Studio 中使用 SSH 连接到 MySQL 数据库可以使用一些第三方工具,例如 putty 或者需要 .NET 环境的 SSH.NET 库。
使用 putty:
1.使用 putty 的 ssh 客户端连接到服务器,配置 ssh 转发。
2.在 Visual Studio 中的 web.config 文件或者配置文件中配置 MySQL 连接字符串,使用本地主机 (localhost 或者 127.0.0.1) 和转发端口 (即 putty 中设置的端口) 作为服务器名称。
使用 .NET 环境中的 SSH.NET 库:
1.在项目中添加 SSH.NET 库的引用。
2.使用 SSH.NET 库的 API 创建 ssh 连接并配置端口转发。
3.在项目中使用转发的本地端口连接到 MySQL 数据库
仅供参考,望采纳,谢谢。