1
0
mirror of https://github.com/kellyjonbrazil/jc.git synced 2025-07-13 01:20:24 +02:00

add sysctl parser

This commit is contained in:
Kelly Brazil
2020-07-08 15:42:06 -07:00
parent aea41ed341
commit beb9174b1b

123
jc/parsers/sysctl.py Normal file
View File

@ -0,0 +1,123 @@
"""jc - JSON CLI output utility sysctl -a Parser
Usage:
specify --sysctl as the first argument if the piped input is coming from sysctl -a
Note: since sysctl output is not easily parsable only a very simple key/value object
will be output. An attempt is made to covert obvious integers. If no conversion
is desired, use the -r (raw) option in jc.
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ sysctl | jc --sysctl -p
{
"user.cs_path": "/usr/bin:/bin:/usr/sbin:/sbin",
"user.bc_base_max": 99,
"user.bc_dim_max": 2048,
"user.bc_scale_max": 99,
"user.bc_string_max": 1000,
"user.coll_weights_max": 2,
"user.expr_nest_max": 32
...
}
$ sysctl | jc --sysctl -p -r
{
"user.cs_path": "/usr/bin:/bin:/usr/sbin:/sbin",
"user.bc_base_max": "99",
"user.bc_dim_max": "2048",
"user.bc_scale_max": "99",
"user.bc_string_max": "1000",
"user.coll_weights_max": "2",
"user.expr_nest_max": "32",
...
}
"""
import jc.utils
class info():
version = '1.0'
description = 'sysctl command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
# details = 'enter any other details here'
# compatible options: linux, darwin, cygwin, win32, aix, freebsd
compatible = ['linux', 'darwin', 'aix', 'freebsd']
magic_commands = ['sysctl']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
Dictionary. Structured data with the following schema:
[
{
"foo": string/integer,
"bar": string/integer,
"baz": string/integer
}
]
"""
for key, value in proc_data.items():
if value.isdigit():
value = int(value)
proc_data[key] = value
return proc_data
def parse(data, raw=False, quiet=False):
"""
Main text parsing function
Parameters:
data: (string) text data to parse
raw: (boolean) output preprocessed JSON if True
quiet: (boolean) suppress warning messages if True
Returns:
Dictionary. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = {}
if jc.utils.has_data(data):
data = data.splitlines()
# linux uses = and bsd uses :
if ' = ' in data[0]:
delim = ' = '
else:
delim = ':'
for line in filter(None, data):
linedata = line.split(delim, maxsplit=1)
key = linedata[0]
value = linedata[1].lstrip()
raw_output[key] = value
if raw:
return raw_output
else:
return process(raw_output)