需要安装ssh.net包
//ssh配置
var sshHost = "127.0.0.1";
var sshUser = "testUser";
var sshPwd = "testPassword";
var sshPort = 22;
//数据库连接
var server = "192.168.1.2";
uint dbPort = 15211;
//ssh连接信息
var auth = new PasswordAuthenticationMethod(sshUser, sshPwd);
ConnectionInfo conInfo = new ConnectionInfo(sshHost, sshPort, sshUser, auth);
try
{
//ssh客户端,用using便于资源释放
using (SshClient client = new SshClient(conInfo))
{
//获取本机ip环回地址 一般是127.0.0.1
var local = IPAddress.Loopback.ToString();
//端口转发
/*
*lcoal 本地绑定ip
*dbPort 本地绑定端口
*server 数据库server
*1521 服务器上数据库的端口
*
*/
ForwardedPortLocal port = new ForwardedPortLocal(local, dbPort, server, 1521);
client.Connect();
if (!client.IsConnected)
{
Console.WriteLine("ssh连接失败");
}
//给客户端追加需要转发的端口信息
client.AddForwardedPort(port);
//启动
port.Start();
/*
* 重点,当我们转发端口之后一定需要将我们转发之后的host和port把MysqlBuilder中的Server和Port替换掉。
* 否则会报Unable to connect to any of the specified MySQL hosts.
*/
//connBuilder.Port = port.BoundPort;//本地绑定ip
//connBuilder.Server = port.BoundHost;//本地绑定ip
//连接字数据库 - 可以更换成其他连接方式 - 此处用的是sqlsugar
var sqlSugarClient = new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = $"Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = {port.BoundHost})(PORT = {port.BoundPort})))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = TEST)));User ID=dbUser;Password=password;",
DbType = DbType.Oracle,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
sqlSugarClient.Open();
var data = sqlSugarClient.SqlQueryable<dynamic>("select * from t_test_table where rownum")?.ToList();
sqlSugarClient.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
[参考]
C#通过ssh连接Mysql数据库
C#通过SSH连接MySql
Connection to MySQL from .NET using SSH.NET Library