2017-09-16 82 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)。