【发布时间】:2020-04-09 05:50:29
【问题描述】:
我正在尝试编写一个程序,允许我与 Ubuntu 虚拟机中本地服务器上的远程数据库进行交互。以下是我可以在 windows 终端中运行以连接数据库的命令,这些命令与我想在程序中执行以与数据库通信的命令基本相同。
>ssh user@192.168.0.60
user@192.168.0.60's password: *********
>sudo mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 101
Server version: 5.7.27-0ubuntu0.18.04.1 (Ubuntu)
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
我可以轻松建立ssh连接,我可以执行ls之类的命令并查看当前目录的内容。但是当我尝试执行sudo mysql 之类的命令时,程序似乎进入了一个循环——我猜是因为它会提示输入密码,但我不知道在提示时如何提供密码。
我将在下面添加连接代码。我真的只需要能够通过连接运行选择语句以从 MySQL 数据库中检索数据。
using System;
using Renci.SshNet;
namespace DBconnector
{
class Program
{
private static string username = "user";
private static string password = "password";
private static string host = "192.168.0.60";
static void Main(string[] args)
{
SshClient client = new SshClient(host, 22, username, password);
client.Connect();
if (!client.IsConnected)
{
Console.WriteLine("Connection Error: Failed");
System.Environment.Exit(1);
}
SshCommand dir = client.RunCommand("...some command..."); // This is where I want to run 'sudo mysql'
// and here I need to be able to change DB and select from tables
Console.WriteLine(dir.Result);
}
}
}
谢谢!
【问题讨论】:
-
有 EntityFramework(.Core) 之类的 MySQL 库或者更糟糕的东西哈哈,完全不需要通过 SSH 连接。
-
点网的mysql连接器也可以ssh dev.mysql.com/doc/connector-net/en/…
-
这里的说明可能会有所帮助:mysqlconnector.net/tutorials/connect-ssh
标签: c# mysql .net database ssh.net