如何通过SSH正确运行“top”命令?

时间:2013-05-14 12:55:43

标签: c# ssh command

我正在使用这个库来连接我运行和运行的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; }
    }
}

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

使用此:top -n1b

使用命令行参数b

批量&#39;批次&#39;模式,可用于发送 从顶部输出到其他程序或文件。在这 模式,top将不接受输入并运行直到迭代 限制你使用&#39; -n&#39;命令行选项或直到 杀死。

更多帮助信息,请参阅man top

BTW -

好的代码示例,这是我的代码版本参考:)

使用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);
    }
}