在SSH.NET中逐行读取和处理命令输出

问题描述 投票:1回答:1

我正在做一个家庭项目,该项目需要通过SSH执行一些命令,读回响应并将其显示在网页上。它在很多时候都可以正常工作,但是有时我会出现一些不一致的行为,例如,错过了某些输出行,这些行会指示下一步该做什么,这导致会话挂起,并且需要还原IIS。

我已经在下面添加了代码,就像我说的那样,我不是一个全职的开发人员,所以会变得一团糟,但是希望有人可以指出正确的方向,以了解我错了什么,以及我需要做什么。更改,我不会了解您是否刚刚过去的代码片段,我更想尝试尝试修复我的问题。

using (SshClient ssh = new SshClient("192.168.0.119", "x", "x."))
{
    ssh.Connect();
    ShellStream shell = ssh.CreateShellStream("Tail", 0, 0, 0, 0, 1024);
    StreamWriter wr = new StreamWriter(shell);
    StreamReader rd = new StreamReader(shell);
    wr.AutoFlush = true;
    if (extract)
    {
        Console.WriteLine("Downloading DataZIP");
        ssh.RunCommand("wget " + zipURL);
    }

    bool reading = shell.CanRead;
    wr.WriteLine("cd " + remoteFilePath + packagename + " && docker build -t dockerfile .");

    while (reading)
    {
        Clients.Caller.builderOut(shell.ReadLine().ToString());
        if (shell.ReadLine().ToString().Contains("Successfully"))
        {
            Clients.Caller.builderOut("Build Complete");
            reading = false;
        }
        if (shell.ReadLine().ToString().Contains("returned a non-zero code: "))
        {
            goto end;
        }
    }

    if (data.Type == TemplateType.Data)
    {
        wr.WriteLine("cd " + remoteFilePath + packagename + " && docker tag dockerfile " + data.Repository + "/" + data.packagename.ToLower() + ":data.Type");
        wr.WriteLine("cd " + remoteFilePath + packagename + " && docker push " + data.Repository + "/" + data.packagename.ToLower() + ":data.Type");
    }

    reading = shell.CanRead;
    while (reading)
    {
        Clients.Caller.builderOut("Pushing this will take a moment");
        if (shell.ReadLine().ToString().Contains("digest:"))
        {
            Clients.Caller.builderOut("Pushed");
            reading = false;
        }
    }

    Clients.Caller.builderOut("End");
    ssh.Disconnect();
    ssh.Dispose();
}

我认为我做错了我想我由于读取控制台输出的方式而收到这些错误。我认为数据变化如此之快,我们会错过一些:

while (reading)
{
    Clients.Caller.builderOut(shell.ReadLine().ToString());
    if (shell.ReadLine().ToString().Contains("Successfully"))
    {
        Clients.Caller.builderOut("Build Complete");
        reading = false;
    }
    if (shell.ReadLine().ToString().Contains("returned a non-zero code: "))
    {
        goto end;
    }
}

因此,使用该输出的3个检查中的每一个,我都可能会丢失某些行,因为输出非常快,而其读取值却发生了变化,因此下一个检查将检查不同的初始化数据,因此我们将跳过出口线或下一个作业线。

c# .net ssh stream ssh.net
1个回答
0
投票

您必须将读取的行存储到变量中,并根据存储的值进行检查:

while (reading)
{
    string line = shell.ReadLine();
    Clients.Caller.builderOut(line);
    if (line.Contains("Successfully"))
    {
        Clients.Caller.builderOut("Build Complete");
        reading = false;
    }
    if (line.Contains("returned a non-zero code: "))
    {
        goto end;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.