开发者

What's the most intelligent way to parse a command's stdout into a usable javascript object

开发者 https://www.devze.com 2023-02-17 16:00 出处:网络
I\'m writing a node.js application where I need to do a lot of parsing of stdout for various commands into javascript objects that I can send to the browser over a websocket c开发者_运维技巧onnection.

I'm writing a node.js application where I need to do a lot of parsing of stdout for various commands into javascript objects that I can send to the browser over a websocket c开发者_运维技巧onnection.

Lets use ping as an example. I want to send back the stdout

64 bytes from ip.isp.com (123.123.123.123): icmp_seq=2 ttl=53 time=7.92 ms

as an object like

{
  'icmp_seq': 2,
  'ttl': 53,
  'time': '7.92 ms'
}

There are a number of different commands I want to do this too, including nmap, so I want to make sure I'm doing it as efficiently and intelligently as possible. My plan right now is to just do splits and regex matches but I want to make sure I'm not missing something.


Try this regular expression:

^(?<Size>\d+) bytes from (?<DestinationHost>[^\s]+) \((?<DestinationIP>.+?)\): icmp_seq=(?<ICMPSequence>\d+) ttl=(?<TTL>\d+) time=(?<Time>.+)$

Run this with the multi-line option. You will have to tweak it to work with all output you may receive but for the line you posted it will work.

Once you have the result you can pull each match out into its own variable or into a JSON object.


Splits and regex matches are probably what I'd do, at least for fairly simple commands like ping. For anything significantly more complex, you may have to create a rudimentary (or even non-rudimentary) parser.


Back a million years ago, I developed some some monitoring software (Tivoli) that used CLI commands to collect system info. What I did was to make heavy use of "awk" the end of a pipe from the command output. The line-oriented nature of native CLI tools like that are (sometimes) an easy way of chopping up CLI output for "screen scraping" purposes.


Many 'beefy' command line utilities will have special output modes which are intended to be easily parsed. For instance, I know nmap has -oX for XML output and it will hopefully be straightforward to convert that to JSON.

Here is more info on nmap:

http://nmap.org/book/man-output.html

So I highly recommend researching each command line utility and looking for "parse intended" output options.

If you do go the regex route, be sure to be as forgiving as possible. Rather than capture the entire stdout buffer and attempt to parse the entire thing as one global match, I would attempt to grab specific sub-patterns for the info you're looking for but ymmv.

But long story short, dont' reinvent the wheel here. I expect that for every different util there is at least one page/thread online where someone has done this already.

0

精彩评论

暂无评论...
验证码 换一张
取 消