使用 SshNet 从远程服务器检索文件夹列表(SSH 交互式客户端)

Using SshNet to Retrieve Folder List from Remote Server (SSH Interactive Client)

我正尝试在 C# 中创建交互式 SSH 客户端会话。我正在使用 Renci.SshNet 库来完成此操作。为了获得概念证明,我只对连接到服务器、运行 "ls" 命令以及检索当前目录中的文件夹列表感兴趣。

我已经能够做到这一点,但是,我在我的输出中得到(我相信)服务器域以及文件名。我在底部提供了一张图片,以准确显示我得到的东西。我不确定如何解析这个......或者我什至以正确的方式这样做?我已经提供了我的代码、输出图片以及我希望的输出结果。

// using....
using Renci.SshNet;

class Program
{
    private const String NEWLINE = "\n";
    private bool connected = false;
    static void Main(string[] args)
    {
        Console.Write("Enter hostname: ");
        String hostname = Console.ReadLine();
        Console.Write("Enter username: ");
        String username = Console.ReadLine();
        Console.Write("Enter password: ");
        String password = Console.ReadLine();


        PasswordAuthenticationMethod pw = new PasswordAuthenticationMethod(username, password);
        ConnectionInfo ci = new ConnectionInfo(hostname, username, pw);
        SshClient ssh = new SshClient(ci);

        Console.Write("-Connecting...\n");
        ssh.Connect();

        IDictionary<Renci.SshNet.Common.TerminalModes, uint> termkvp = new Dictionary<Renci.SshNet.Common.TerminalModes, uint>();
        termkvp.Add(Renci.SshNet.Common.TerminalModes.ECHO, 53);
        ShellStream shellStream = ssh.CreateShellStream("xterm", 80, 24, 800, 600, 1024, termkvp);

        String line = null;
        String s = null;

        TimeSpan timeout = new TimeSpan(0, 0, 1);
        while ((s = shellStream.ReadLine(timeout)) != null)
        {
            Console.WriteLine(s);
        }
        shellStream.Flush();

        while((line = Console.ReadLine()) != "exit")
        {
            shellStream.Write(line);
            shellStream.Write(NEWLINE);

            while ((s = shellStream.ReadLine(timeout)) != null)
            {
                Console.WriteLine(s);
            }
            shellStream.Flush();
        }
        Console.Write("Press any key to continue...");
        Console.ReadLine();
    }
}

输出:

(我已经突出显示了我感兴趣的部分)

预期输出:

- Connecting...
Last login: Thu Apr 30 10:28:12 2015 from ...
ls     (user input)
    2015-03-18_0
    First_HFSS_Test
    First_Test
    ...

编辑

当我使用 "dir" 而不是 "ls" 时,我得到的是没有其他信息的目录列表。我相信 "ls" 给了我带有颜色信息的列表。也许目录列表之外的信息是经过翻译的颜色数据???

这些是 ANSI Escape Sequences,不仅用于编码颜色指令,有时还用于指定光标移动和绘制区域。

您正在获取交互式控制代码,因为 a terminal is not a shell. The shell considers the terminal on output decisions and your solution is probably in disabling aliases (actually, their parameters). This answer 建议使用 /bin/ls 的完整路径、引用 "ls" 'ls'、反斜杠 \ls 或使用命令替换:$(which ls).

另请注意链接答案上方的评论:可能需要输出重定向,以便命令不会截断其输出,因为它们适应封闭终端的 window 尺寸。这有点令人费解,但也应该完成工作。