1

我正在使用这个库连接到我运行和运行的 Linux 命令,但有些命令有问题

例如,我在运行这些命令时遇到问题:

顶部和顶部 -n 1

错误:未设置TERM环境变量

private void button2_Click(object sender, EventArgs e)
{
        Renci.SshNet.SshClient sshClient = new Renci.SshNet.SshClient("192.168.150.128", "reza", "1");
        sshClient.Connect();
        var command = sshClient.RunCommand("top");

        var line = command.Result.Split('\n');
        List<ServerStatusCpu> serverstatus = new List<ServerStatusCpu>();
        for (int i = 3; i < line.Length - 1; i++)
        {
            var li = line[i];
            var words = li.Split(' ');
            List<string> fillterwords = new List<string>();

            foreach (var w in words)
            {
                if (w != "")
                {
                    fillterwords.Add(w);
                }
            }

            ServerStatusCpu serverStatus = new ServerStatusCpu();
            serverStatus.Time = fillterwords[0];
            serverStatus.TimeType = fillterwords[1];
            serverStatus.Name = fillterwords[2];
            serverStatus.UserCpuTime = float.Parse(fillterwords[3].Replace("%", ""));
            serverStatus.UserNiceCpuTime = float.Parse(fillterwords[4].Replace("%", ""));
            serverStatus.SystemCpuTime = float.Parse(fillterwords[5].Replace("%", ""));
            serverStatus.IoWaitCpuTime = float.Parse(fillterwords[6].Replace("%", ""));
            serverStatus.IrqCpuTime = float.Parse(fillterwords[7].Replace("%", ""));
            serverStatus.SoftwareIrqCpuTime = float.Parse(fillterwords[8].Replace("%", ""));
            serverStatus.StealCpuTime = float.Parse(fillterwords[9].Replace("%", ""));
            serverStatus.GuestCpuTime = float.Parse(fillterwords[10].Replace("%", ""));
            serverStatus.IdleCpuTime = float.Parse(fillterwords[11].Replace("%", ""));

            serverstatus.Add(serverStatus);
        }
        dataGridView1.DataSource = serverstatus;
 }


class ServerStatusCpu
{
   public class ServerStatusCpu
   {
        public string Time { get; set; }

        public string TimeType { get; set; }

        public string Name { get; set; }

        public float UserCpuTime { get; set; }

        public float SystemCpuTime { get; set; }

        public float UserNiceCpuTime { get; set; }

        public float IdleCpuTime { get; set; }

        public float IoWaitCpuTime { get; set; }

        public float IrqCpuTime { get; set; }

        public float SoftwareIrqCpuTime { get; set; }

        public float StealCpuTime { get; set; }

        public float GuestCpuTime { get; set; }
    }
}
4

2 回答 2

1

您遇到的问题与服务器不知道应该将输入重定向到哪个 TERM 的事实有关。

请查看http://www.linuxquestions.org/questions/programming-9/term-environment-variable-not-set-593180/

您需要设置 TERM 变量才能获得任何输出。

于 2013-05-14T13:12:57.840 回答
1

用这个:top -n1b

使用命令行参数b

以“批处理”模式启动顶部,这对于将输出从顶部发送到其他程序或文件可能很有用。在这种模式下,top 将不接受输入并运行,直到您使用 '-n' 命令行选项设置的迭代限制或直到被杀死。

更多帮助信息见man top

顺便提一句 -

不错的代码示例,这是我对您的代码的版本参考 :)

使用MoreLINQ,还需要添加一些代码来返回结果。

static void ParseTop(string contentOfOutput)
{
    var line = contentOfOutput.Split('\n');

    //parse uptime/user/load.avg
    var lineUud = line[0].Substring("top -".Length);

    var wordsUud = lineUud.Split(new[] { "up", "load average:", ",", " " }, StringSplitOptions.RemoveEmptyEntries);
    //00:00:00 up 0  days, 17:51,  0  users,  load average: 0.00, 0.01, 0.05
    //^0          ^1 ^2    ^3      ^4 ^5(unused)            ^6    ^7    ^8
    //00:00:00 up 0  min,  1  user,  load average: 0.00, 0.01, 0.05
    //^0          ^1 ^2    ^3 ^4(unused)           ^5    ^6    ^7

    var time = TimeSpan.Parse(wordsUud[0]);
    if (wordsUud[2] == "days")
    {
        var uptime = TimeSpan.Parse(wordsUud[1] + "." + wordsUud[3] + ":00");
        var users = int.Parse(wordsUud[4]);
        var la1Min = float.Parse(wordsUud[5]);
        var la5Min = float.Parse(wordsUud[6]);
        var la15Min = float.Parse(wordsUud[7]);
    }
    else
    {
        var uptime = TimeSpan.Parse("00:" + wordsUud[1] + ":00");
        var users = int.Parse(wordsUud[3]);
        var la1Min = float.Parse(wordsUud[4]);
        var la5Min = float.Parse(wordsUud[5]);
        var la15Min = float.Parse(wordsUud[6]);
    }


    //parse tasks
    var lineTasks = line[1].Substring("Tasks:".Length);

    var wordTasks = lineTasks.Split(new[] { "total", "running", "sleeping", "stopped", "zombie", ",", " " }, StringSplitOptions.RemoveEmptyEntries);
    //70 total,   1 running,  69 sleeping,   0 stopped,   0 zombie
    //^0          ^1          ^2             ^3           ^4
    var totalTasks = int.Parse(wordTasks[0]);
    var runningTasks = int.Parse(wordTasks[1]);
    var sleepingTasks = int.Parse(wordTasks[2]);
    var stoppedTasks = int.Parse(wordTasks[3]);
    var zombieTasks = int.Parse(wordTasks[4]);

    //parse cpu
    var cpus = new Dictionary<string, Dictionary<string, float>>();

    var cpuLineIndex = 2;
    string cpuLine;
    while ((cpuLine = line[cpuLineIndex]).StartsWith("%Cpu"))
    {
        var wordCpu = cpuLine.Split(new[] { "%Cpu", ":", ",", " " }, StringSplitOptions.RemoveEmptyEntries);
        //%Cpu(s):  0.2 us,  0.6 sy,  0.0 ni, 99.1 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
        //%Cpu1  :  0.2 us,  0.6 sy,  0.0 ni, 99.1 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
        //    ^0    ^1  ^2   ^3  ^4   ^5  ^6  ^7   ^8   ^9  ^10  ^11 ^12  ^13 ^14  ^15 ^16

        var cpu = new Dictionary<string, float>();
        foreach (var entry in wordCpu.Skip(1).Batch(2).Where(p => p.Count() == 2).Select(p => p.ToArray()))
        {
            cpu[entry[1]] = float.Parse(entry[0]);
        }

        cpus[wordCpu[0]] = cpu;
        cpuLineIndex++;
    }

    //parse memory/swap
    var memories = new Dictionary<string, Dictionary<string, int>>();

    var memLineIndex = cpuLineIndex;
    string memLine;
    while ((memLine = line[memLineIndex]).StartsWith("KiB"))
    {
        var wordMem = memLine.Split(new[] { "KiB", ":", ",", " " }, StringSplitOptions.RemoveEmptyEntries);
        //KiB Mem:    993780 total,   968936 used,    24844 free,   418236 buffers
        //KiB Swap:   524284 total,        0 used,   524284 free,   506312 cached
        //    ^0      ^1     ^2       ^3     ^4      ^5     ^6      ^7     ^8

        var mem = new Dictionary<string, int>();
        foreach (var entry in wordMem.Skip(1).Batch(2).Where(p => p.Count() == 2).Select(p => p.ToArray()))
        {
            mem[entry[1]] = int.Parse(entry[0]);
        }

        memories[wordMem[0]] = mem;
        memLineIndex++;
    }


    //parse process
    var process = new List<Dictionary<string, string>>();

    var lineNumOfBlank = Array.IndexOf(line, "");
    var headers = line[lineNumOfBlank + 1].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

    for (var i = lineNumOfBlank + 2; i < line.Length - 1; i++)
    {
        var li = line[i];
        var strings = li.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        var dic = new Dictionary<string, string>();
        for (var j = 0; j < headers.Length; j++)
        {
            dic[headers[j]] = strings[j];
        }

        if (strings.Length > headers.Length) //process name has space?
        {
            for (var j = headers.Length; j < strings.Length; j++)
            {
                dic[headers[headers.Length - 1]] += " " + strings[j];
            }
        }

        process.Add(dic);
    }
}
于 2015-09-12T09:24:32.343 回答