C# 利用ssh 开启一个命令交互窗口

发布于:2025-02-10 ⋅ 阅读:(45) ⋅ 点赞:(0)

        本文记录C#如何利用ssh远程连接服务器,并开启一个命令交互窗口。

首先创建一个控制台项目,再nuget 中搜索ssh,安装这个包:

 然后拷贝我下面的代码:

// See https://aka.ms/new-console-template for more information
using System;
using System.Diagnostics;
using Renci.SshNet;

class Program
{
    static void Main(string[] args)
    {
        // SSH 连接信息
        string host = "172.16.3.39"; // 例如: "192.168.1.1"
        string username = "rykj";
        string password = "rykj"; // 或者使用密钥文件

        // 创建 SSH 客户端
        using (var client = new SshClient(host, username, password))
        {
            try
            {
                // 连接到服务器
                client.Connect();
                Console.WriteLine("Connected to server.");

                // 打开一个新的 SSH shell 会话
                using (var shellStream = client.CreateShellStream("shell", 80, 24, 800, 600, 1024))
                {
                    // 读取输出的任务
                    Task.Run(() =>
                    {
                        string? output;
                        while (true)
                        {
                            output = shellStream.ReadLine();
                            if (output != null)
                            {
                                Console.WriteLine(output);
                            }
                        }
                    });

                    // 输入命令的循环
                    string? command;
                    while (true)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write("Enter command: ");
                        Console.ResetColor();
                        command = Console.ReadLine();

                        if (string.IsNullOrEmpty(command))
                            break;

                        shellStream.WriteLine(command);
                    }
                }

                // 断开连接
                client.Disconnect();
                Console.WriteLine("Disconnected from server.");
            }
            catch (Exception ex) 
            {
                Console.WriteLine($"Error: {ex.Message}");         
            }
        }
    }
}

注意:将连接信息修改为你需要连接的服务器(ip,用户名,密码)

        // SSH 连接信息
        string host = "172.16.3.39"; // 例如: "192.168.1.1"
        string username = "rykj";
        string password = "rykj"; // 或者使用密钥文件

运行后就可以看到控制台编程交互式的,宛如再服务器本机的终端窗口:

        需要说明的是,为了避免输入输出相互阻塞,这里读取输出采用另一个线程执行。


网站公告

今日签到

点亮在社区的每一天
去签到