首页 > 解决方案 > 从 C# 到 MySQL 实例的 SSH 和 sudo 连接

问题描述

我正在尝试编写一个程序,允许我与 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);
        }
    }
}

谢谢!

标签: c#mysql.netdatabasessh.net

解决方案


对于您的字面问题,请参阅:

但是,以这种方式自动化sudo是一种不好的做法:


我相信您实际上会希望通过 SSH 隧道连接 MySQL:

(除非您的数据库服务器实际上允许直接连接)


推荐阅读