2017-09-16 79 views
0

我试图捕获AIX的实时信息,如CPU,内存,IO负载与C#控制台应用程序,因为我想在第三部分自定义仪表板中显示该信息。 运行命令TOPAS后,我需要周期性地捕捉整个以下文字:如何读取AIX topas命令导致c#

enter image description here

我试着用下面的代码,我在一些论坛上发现捕捉到它:

using Renci.SshNet; 
using System; 
using System.IO; 
using System.Threading; 

namespace SSH_check_commands 
{ 
public class MyAsyncInfo 
{ 
    public MyAsyncInfo(Byte[] array, ShellStream stream) 
    { 
     ByteArray = array; 
     Stream = stream; 
    } 

    public Byte[] ByteArray { get; set; } 
    public ShellStream Stream { get; set; } 
} 

class Program 
{ 
    private static ShellStream stream; 
    private static SshClient client; 
    private static byte[] _data = new byte[2048]; 
    static void Main(string[] args) 
    { 
     client = new SshClient("host", "user", "password"); 
     client.Connect(); 
     stream = client.CreateShellStream(@"xterm", 80, 24, 800, 600, 1024); 
     stream.DataReceived += StartAsyncRead; 
     stream.Write("bash\n"); 
     Thread.Sleep(5000); 
     stream.Write("topas -i 10\n"); 
     Console.ReadLine(); 
    } 

    private static void StartAsyncRead(object sender, EventArgs e) 
    { 
     try 
     { 
      stream.BeginRead(_data, 0, _data.Length, OnReadCompletion, new MyAsyncInfo(_data, stream)); 

     } 
     catch (Exception exception) 
     { 
      Console.WriteLine(exception); 
     } 
    } 

    private static void OnReadCompletion(IAsyncResult ar) 
    { 
     try 
     { 
      var mai = (MyAsyncInfo)ar.AsyncState; 
      int datalen = mai.Stream.EndRead(ar); 
      string line = client.ConnectionInfo.Encoding.GetString(mai.ByteArray, 0, datalen); 
      Console.Write(line); 
     } 
     catch (Exception exception) 
     { 
      Console.WriteLine(exception); 
     } 
    } 
    public static string SendCommand(string cmd, ShellStream sh) 
    { 
     StreamReader reader = null; 
     try 
     { 
      reader = new StreamReader(sh); 
      StreamWriter writer = new StreamWriter(sh); 
      writer.AutoFlush = true; 
      writer.WriteLine(cmd); 
      while (sh.Length == 0) 
      { 
       Thread.Sleep(1000); 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("exception: " + ex.ToString()); 
     } 
     return reader.ReadToEnd(); 
    } 
} 
} 

但我不能解析的结果,因为它没有结构:

enter image description here

你能帮我吗?

回答

0

结果是结构化。那些是ANSI escape codes。您可以解析这些内容,就像您的SSH终端客户端解析这些内容以显示不错的输出一样。

但这是一项艰巨的任务。见SSH.NET based colored terminal emulator


虽然我会说,试图解析旨在用于人用命令的输出是一个坏主意,摆在首位。当然,还有另一种方式可以以更容易解析的格式检索相同的信息。但这是另一个网站的问题(例如Super User)。