我尝试使用C#控制台应用程序捕获AIX,CPU,内存,IO负载等实时信息,因为我想在第三方自定义仪表板中显示该信息。 运行命令topas后,我需要定期捕获以下全文:
我尝试使用我在某个论坛中找到的以下代码捕获它:
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();
}
}
}
但我无法解析结果,因为它没有结构化:
你能帮我吗?
解决方法:
我已经改变了解决问题的方法。 我无法通过ssh流捕获全文,因为我只收到了更改的字符。 因此,我会定期运行以下ssh命令将nmon内容保存在一个文件中(名为 hostname_YYMMDD_H24_mm.nmon ):
nmon -f -c 1
使用cat命令后,我可以读取文件,提取内容,转换内容并将其加载到仪表板中。
答案 0 :(得分:0)
结果是结构化。这些是ANSI escape codes。您可以解析这些,就像您的SSH终端客户端解析那些显示良好输出的方式一样。
但这是一项艰巨的任务。请参阅SSH.NET based colored terminal emulator。虽然我会说尝试解析用于人类使用的命令的输出是一个坏主意,但首先。可以肯定的是,还有另一种方法可以以更易于解析的格式检索相同的信息。但这是另一个网站的问题(例如Super User)。
如果您只想剥离ANSI转义码,可以使用正则表达式,如How to remove ^[, and all of the escape sequences in a file using linux shell scripting所示:
s = new Regex(@"\x1B\[[^@-~]*[@-~]").Replace(s, "");