1
0
mirror of https://github.com/kellyjonbrazil/jc.git synced 2026-04-03 17:44:07 +02:00

Compare commits

...

222 Commits

Author SHA1 Message Date
Kelly Brazil
c72562524b fully remove tests from packaging 2020-05-08 09:30:31 -07:00
Kelly Brazil
b7dd6441c7 version bump 2020-05-08 08:20:33 -07:00
Kelly Brazil
31fcc2f755 remove manifest.in - no longer needed due to removing tests 2020-05-08 08:20:21 -07:00
Kelly Brazil
b391aa14bc add license_file to metadata 2020-05-08 08:19:51 -07:00
Kelly Brazil
d3c45debbb remove tests and add license file 2020-05-08 08:19:31 -07:00
Kelly Brazil
5b08469b87 Merge pull request #57 from kellyjonbrazil/dev
Dev v1.10.7
2020-05-01 15:55:50 -07:00
Kelly Brazil
4a77ec63a4 add IfconfigParser class 2020-05-01 14:57:50 -07:00
Kelly Brazil
d13606b6dc modify dependencies for easier packaging into Fedora 2020-05-01 14:37:23 -07:00
Kelly Brazil
05291c93bb vendorize ifconfig-parser module for easier packaging in Fedora 2020-05-01 14:36:54 -07:00
Kelly Brazil
8cf00a208e change text to strings 2020-04-29 15:57:55 -07:00
Kelly Brazil
06d73c8876 formatting 2020-04-23 07:06:44 -07:00
Kelly Brazil
649c646ea2 add brew install option 2020-04-22 16:08:34 -07:00
Kelly Brazil
b7756d9250 version bump 2020-04-20 16:33:26 -07:00
Kelly Brazil
1cd2cd954c remove references to homebrew/shim to allow tests to pass in homebrew packaging ci/cd 2020-04-20 16:31:22 -07:00
Kelly Brazil
72020b8da9 move packages info to jc-packages github page 2020-04-17 10:20:25 -07:00
Kelly Brazil
cf9720b749 update install info 2020-04-16 14:03:31 -07:00
Kelly Brazil
967b9db7f9 spelling 2020-04-15 21:27:22 -07:00
Kelly Brazil
bb3acb1182 formatting 2020-04-15 21:25:06 -07:00
Kelly Brazil
560c7f7e6d formatting 2020-04-15 21:23:55 -07:00
Kelly Brazil
79b2841764 add new binary package install info 2020-04-15 21:22:43 -07:00
Kelly Brazil
a06a89cbd1 version bump 2020-04-14 11:15:24 -07:00
Kelly Brazil
431bd969eb use sys.exit(0) instead of exit() 2020-04-14 11:10:31 -07:00
Kelly Brazil
c87b722aec spelling 2020-04-12 13:23:58 -07:00
Kelly Brazil
3688b8b014 Merge pull request #56 from kellyjonbrazil/dev
Dev v1.10.4
2020-04-12 13:21:38 -07:00
Kelly Brazil
07b8d9e0c0 version bump 2020-04-12 13:18:28 -07:00
Kelly Brazil
7454b53e39 formatting 2020-04-12 13:13:28 -07:00
Kelly Brazil
3d6a76024d update with JC_COLORS info 2020-04-12 13:10:57 -07:00
Kelly Brazil
421b980957 JC_COLORS working 2020-04-12 13:03:09 -07:00
Kelly Brazil
4a22e27d6a add set_env_colors function 2020-04-12 12:43:51 -07:00
Kelly Brazil
99f7842dee fix brek on pipe error 2020-04-09 13:38:33 -07:00
Kelly Brazil
7f869b4b18 change colors to ansi and match jello style 2020-04-09 07:31:21 -07:00
Kelly Brazil
9665f4ee84 add pypi badge 2020-04-07 08:44:15 -07:00
Kelly Brazil
606904d48b Merge pull request #53 from kellyjonbrazil/dev
Dev v1.10.1
2020-04-04 17:28:21 -07:00
Kelly Brazil
3f5279b97c version bump to 1.10.1 2020-04-04 17:25:55 -07:00
Kelly Brazil
f5ec21e6ac use in instead of find() 2020-04-04 17:19:32 -07:00
Kelly Brazil
578a284465 use in instead of find() 2020-04-04 17:18:39 -07:00
Kelly Brazil
422e392d9d use in instead of find() 2020-04-04 17:17:43 -07:00
Kelly Brazil
54dfffd34a use in instead of find() 2020-04-04 17:16:25 -07:00
Kelly Brazil
cffba64d2b use in and startswith() instead of find() 2020-04-04 17:15:03 -07:00
Kelly Brazil
56a0c12a59 use in instead of find() 2020-04-04 17:12:22 -07:00
Kelly Brazil
c174d3de18 use in and startswith() instead of find() 2020-04-04 17:10:46 -07:00
Kelly Brazil
a9c59ef9fc fix logic to not for ' type ' in cleandata[0] 2020-04-04 17:07:38 -07:00
Kelly Brazil
abdb9b2673 use in instead of find() 2020-04-04 17:05:17 -07:00
Kelly Brazil
548aaab626 remove old commented code 2020-04-04 17:04:20 -07:00
Kelly Brazil
20571c87ae us in instead of find() 2020-04-04 17:01:56 -07:00
Kelly Brazil
19e49200de version bump 2020-04-04 16:59:48 -07:00
Kelly Brazil
d32f5c67a9 use startswith() instead of find() 2020-04-04 16:59:03 -07:00
Kelly Brazil
b83b626435 use startswith() instead of find() 2020-04-04 16:57:23 -07:00
Kelly Brazil
ab2c1b25ec use startswith() and in instead of find() 2020-04-04 16:56:11 -07:00
Kelly Brazil
f2d46313a4 use startswith() instead of find() 2020-04-04 16:53:55 -07:00
Kelly Brazil
87e4796a6c use in instead of .find() 2020-04-04 16:52:45 -07:00
Kelly Brazil
0014a5c2f4 us startswith() and in instead of .find() 2020-04-04 16:51:36 -07:00
Kelly Brazil
7af56e0dad use startswith() and in instead of find() 2020-04-04 16:50:05 -07:00
Kelly Brazil
a5ae6e3c01 use startswith() instead of find() 2020-04-04 16:48:16 -07:00
Kelly Brazil
fe1a0d1faf use in instead of .find() 2020-04-04 16:46:09 -07:00
Kelly Brazil
302f05cdda prettify style block 2020-04-03 14:50:20 -07:00
Kelly Brazil
c0044be7b0 rename color grey to gray 2020-04-03 14:48:19 -07:00
Kelly Brazil
0110078807 update badge 2020-04-03 14:47:08 -07:00
Kelly Brazil
42eacb45f8 rename to Tests 2020-04-03 14:45:04 -07:00
Kelly Brazil
a43e2e1991 add -m option info 2020-04-02 17:40:06 -07:00
Kelly Brazil
c8b721d4f6 version bump to 1.10.0 2020-04-02 17:35:35 -07:00
Kelly Brazil
d0bfddc3d9 add color and -m monochrome option 2020-04-02 17:29:25 -07:00
Kelly Brazil
6b925a16c8 add tests badge 2020-04-02 10:55:32 -07:00
Kelly Brazil
89ebd9fc22 add axfr info to schema 2020-03-27 07:31:08 -07:00
Kelly Brazil
6b4ba66231 Merge pull request #52 from kellyjonbrazil/dev
Dev v1.9.3
2020-03-26 17:15:13 -07:00
Kelly Brazil
5b697dc381 add more dig tests 2020-03-26 17:09:29 -07:00
Kelly Brazil
9ba73c95d1 add tests 2020-03-26 16:45:29 -07:00
Kelly Brazil
93aa390447 version bump to v1.9.3 2020-03-26 16:30:17 -07:00
Kelly Brazil
3cfb8945dd use startswith() instead of find 2020-03-26 16:29:59 -07:00
Kelly Brazil
cd8d38f2a1 add axfr support 2020-03-26 16:22:53 -07:00
Kelly Brazil
8ec8cd6294 Merge pull request #50 from kellyjonbrazil/dev
Dev v1.9.2
2020-03-12 17:09:04 -07:00
Kelly Brazil
c028113561 version bump to v1.9.2 2020-03-12 17:06:55 -07:00
Kelly Brazil
5f22e1c803 fix and test for osx arp entries without ifscope 2020-03-12 17:02:26 -07:00
Kelly Brazil
d3351787e5 change osx detection 2020-03-12 16:52:33 -07:00
Kelly Brazil
e5bea9ae3b version bump 2020-03-12 08:52:01 -07:00
Kelly Brazil
93c710abe9 Merge pull request #49 from kellyjonbrazil/dev
Dev v1.9.1
2020-03-12 08:23:10 -07:00
Kelly Brazil
c29e7cfe5c version bump to 1.9.1 2020-03-12 08:17:28 -07:00
Kelly Brazil
cb5c1ba00d add tests for fix to make the file parser splitting more robust 2020-03-11 17:04:48 -07:00
Kelly Brazil
9a012b94e1 make splitting more robust 2020-03-11 15:40:34 -07:00
Kelly Brazil
400f5a44ec Merge pull request #48 from kellyjonbrazil/dev
Dev v1.9.0
2020-03-11 13:37:22 -07:00
Kelly Brazil
a2ab5bab91 version bump to v1.9.0 2020-03-11 13:32:58 -07:00
Kelly Brazil
fc8ab27361 bugfix for misaligned columns and additional test for ntpq #31 2020-03-11 13:24:55 -07:00
Kelly Brazil
59f19d33a5 add file command tests for #41 2020-03-11 12:39:59 -07:00
Kelly Brazil
dfc9618115 add file parser for issue #41 2020-03-11 12:20:58 -07:00
Kelly Brazil
8e02e5c75a fix issue with getting options with some commands #47 2020-03-11 09:21:14 -07:00
Kelly Brazil
970493ab93 add magic commands 2020-03-11 06:22:54 -07:00
Kelly Brazil
64d78956eb update acknowledgment 2020-03-10 22:18:26 -07:00
Kelly Brazil
40c05346f4 re-adding optimizations from https://github.com/philippeitis 2020-03-10 22:16:40 -07:00
Kelly Brazil
e9b0bc1409 doc update 2020-03-10 22:03:54 -07:00
Kelly Brazil
798e6bb7d9 tests passing for airport -s. issue #46 2020-03-10 22:03:44 -07:00
Kelly Brazil
12a370deed add airport -s parser for issue #46 2020-03-10 21:51:02 -07:00
Kelly Brazil
553bfbe1a0 tests passing for airport -I. Issue #46 2020-03-10 21:02:17 -07:00
Kelly Brazil
52494321fc fixes and docs for airport parser issue #46 2020-03-10 20:55:07 -07:00
Kelly Brazil
c6c9e06496 added airport command parser 2020-03-10 20:35:52 -07:00
Kelly Brazil
e3a6c05a58 timedatectl fixes, tests, and fixtures for issue #42 2020-03-10 20:26:53 -07:00
Kelly Brazil
391d06f68d change selection_state to state 2020-03-10 20:16:41 -07:00
Kelly Brazil
99804ea06e added timedatectl status parser 2020-03-10 18:37:55 -07:00
Kelly Brazil
51935deb2a timedatectl test fixtures 2020-03-10 18:00:47 -07:00
Kelly Brazil
b24d0c3a47 ntpq docs 2020-03-10 18:00:26 -07:00
Kelly Brazil
762a886d6f add ntpq tests 2020-03-10 15:17:25 -07:00
Kelly Brazil
2c3e9ddfe4 add ntpq parser for issue #31 2020-03-10 14:18:55 -07:00
Kelly Brazil
c7cd2b63c8 delete unused test file 2020-03-09 11:46:17 -07:00
Kelly Brazil
f0528ea831 Merge pull request #45 from kellyjonbrazil/dev
Dev v1.8.1
2020-03-08 14:54:13 -07:00
Kelly Brazil
5bc5596f60 version bump to 1.8.1 2020-03-08 14:49:23 -07:00
Kelly Brazil
2c27ac46be add ls test fixtures 2020-03-08 14:43:51 -07:00
Kelly Brazil
caad840153 Merge pull request #44 from philippeitis/patch-5
Move core magic() logic into seperate function for testability, minor tweaks
2020-03-08 14:19:37 -07:00
philippeitis
65bd7e2904 Merge pull request #1 from kellyjonbrazil/pr/44
Merge changes
2020-03-08 14:10:35 -07:00
Kelly Brazil
c3d7d7db12 removed whitespace 2020-03-08 14:03:08 -07:00
Kelly Brazil
5605310362 added tests, removed os import, changed to 'assertEqual' 2020-03-08 14:02:54 -07:00
philippeitis
17b6efe82e Create basic tests for generate_magic_commands() 2020-03-08 13:35:01 -07:00
philippeitis
a032ae56ae Pass args to generate_magic_command() to allow testing. 2020-03-08 13:26:15 -07:00
philippeitis
eab2f4b056 Move core magic() logic into seperate function for testability, minor tweaks.
We only care about the command when testing magic() - by moving that out, we can easily test the command. I modified the code to return a boolean signalling that the command is valid, and the command itself to maintain the original functionality.

I also made some small tweaks (removed a list() call, fixed a possible bug with no arguments., moved magic_dict instantiation past the fast path checks to avoid making a dict if not needed.)
2020-03-08 13:20:38 -07:00
Kelly Brazil
aff86ae6c7 reimpliment magic() based on the dictionary approach suggested by philippeitis 2020-03-08 12:58:26 -07:00
Kelly Brazil
7ece9ddc1a version bump ls 2020-03-07 17:26:42 -08:00
Kelly Brazil
7cd048e839 changelog update 2020-03-07 17:25:10 -08:00
Kelly Brazil
1e22f610a3 fix for osx - doesn't print 'total xx' line if empty directory (issue #40) 2020-03-07 17:22:08 -08:00
Kelly Brazil
5249c972ae add to changelog 2020-03-06 12:09:20 -08:00
Kelly Brazil
fd45f856a0 import jc.utils instead of jc 2020-03-06 12:09:09 -08:00
Kelly Brazil
c8ab40cd33 ignore .github folder 2020-03-05 09:19:58 -08:00
Kelly Brazil
b2c872925b add utf-8 encoding for testing on Windows 2020-03-04 19:47:03 -08:00
Kelly Brazil
f48e229202 utf-8 open for windows tests 2020-03-04 19:40:32 -08:00
Kelly Brazil
799fec92c3 utf-8 for windows support 2020-03-04 19:33:45 -08:00
Kelly Brazil
87a41c2fca add utf-8 to open function 2020-03-04 19:30:30 -08:00
Kelly Brazil
7f85de0c46 add windows-latest 2020-03-04 19:28:21 -08:00
Kelly Brazil
13661b1993 Merge pull request #37 from philippeitis/continuous_integration
Enable Continuous Integration with GitHub Actions.
2020-03-04 16:54:26 -08:00
philippeitis
51d5c3892d Remove Windows tests, due to lack of support. 2020-03-04 16:21:06 -08:00
philippeitis
e4eab4641a Change line in blkid.py to trigger CI 2020-03-04 16:17:58 -08:00
philippeitis
9b148e0ba3 Add requirements.txt 2020-03-04 16:16:19 -08:00
philippeitis
de28932650 Consolidate dictionary into creation, trigger CI 2020-03-04 16:14:03 -08:00
Kelly Brazil
5f798d603e version bump and ack to philippeitis 2020-03-04 16:11:14 -08:00
Kelly Brazil
a0757b2dd3 optimize line parsing 2020-03-04 16:07:53 -08:00
philippeitis
498d51b4e8 Enable Continuous Integration with GitHub Actions.
This automatically runs unit tests on various operating systems and Python versions when Python files are modified to ensure that functionality remains correct.
2020-03-04 16:07:32 -08:00
Kelly Brazil
b06b6bae3f Merge pull request #36 from philippeitis/patch-3
Simplify process() in history.py, avoid list allocation in parse()
2020-03-04 16:04:05 -08:00
Kelly Brazil
b5eaff2137 Merge pull request #35 from kellyjonbrazil/revert-34-patch-3
Revert "Simplify process() in history.py, avoid list allocation in parse()"
2020-03-04 15:33:13 -08:00
Kelly Brazil
c01bcd3734 Revert "Simplify process() in history.py, avoid list allocation in parse()" 2020-03-04 15:32:23 -08:00
Kelly Brazil
d75c4068ca Merge pull request #34 from philippeitis/patch-3
Simplify process() in history.py, avoid list allocation in parse()
2020-03-04 15:31:55 -08:00
Kelly Brazil
6aa2d5a3d2 Merge pull request #33 from philippeitis/patch-2
Handle case where only options are passed.
2020-03-04 15:28:09 -08:00
philippeitis
065276805f Simplify process() in history.py, avoid list allocation in parse() 2020-03-04 13:35:31 -08:00
philippeitis
a63408c8cf Handle case where only options are passed. 2020-03-04 13:16:35 -08:00
Kelly Brazil
69576f6bfa minor sytax fixes 2020-03-04 12:03:40 -08:00
Kelly Brazil
19845624e2 Merge pull request #32 from philippeitis/patch-1
Simplify main(), magic() methods.
2020-03-04 11:59:29 -08:00
philippeitis
22ff2964e9 Simplify main(), magic() methods. 2020-03-04 10:33:42 -08:00
Kelly Brazil
d96b3a65a9 formatting 2020-03-04 08:30:52 -08:00
Kelly Brazil
4989445ef4 Merge pull request #30 from kellyjonbrazil/dev
Dev v1.8.0
2020-03-03 11:46:09 -08:00
Kelly Brazil
6770892acd add release notes link 2020-03-03 11:37:59 -08:00
Kelly Brazil
d4eba8740f release date 3/3 2020-03-03 11:08:52 -08:00
Kelly Brazil
9f60760560 add group and gshadow tests 2020-03-03 10:54:27 -08:00
Kelly Brazil
0a8f8ac934 add group and gshadow parsers 2020-03-03 09:55:43 -08:00
Kelly Brazil
6ae24c8244 add group and gshadow test fixtures 2020-03-03 09:55:17 -08:00
Kelly Brazil
d3679082a8 add group and gshadow parsers 2020-03-03 09:36:16 -08:00
Kelly Brazil
fb08b42dca change 'group_list' to 'members' 2020-03-03 09:32:56 -08:00
Kelly Brazil
4aeaa9f42a add /etc/gshadow parser 2020-03-03 09:32:25 -08:00
Kelly Brazil
5f5693da04 spelling fix 2020-03-03 09:07:28 -08:00
Kelly Brazil
5eb0f61727 add /etc/group file parser 2020-03-03 09:07:09 -08:00
Kelly Brazil
958e998991 formatting 2020-03-02 17:15:05 -08:00
Kelly Brazil
b78c1509f6 try/except dialect detection 2020-03-02 15:06:25 -08:00
Kelly Brazil
ce184d4d57 add csv parser tests 2020-03-02 15:05:56 -08:00
Kelly Brazil
b4c3714ced removed [OPTIONS] PARSER syntax. still works but prefer the PARSER [OPTIONS] syntax for better performance 2020-03-02 14:10:15 -08:00
Kelly Brazil
5b7dfa0438 formatting 2020-03-02 14:07:56 -08:00
Kelly Brazil
391a388476 doc update 2020-03-02 14:07:29 -08:00
Kelly Brazil
d9c4e2ed4c add csv file parser 2020-03-02 14:03:58 -08:00
Kelly Brazil
0c42db38b1 doc update 2020-03-02 10:30:12 -08:00
Kelly Brazil
2f9be8bf33 simplify usage 2020-03-02 08:32:42 -08:00
Kelly Brazil
e8c00155e8 add -b to warning message 2020-03-02 07:43:45 -08:00
Kelly Brazil
cc88fdd9ee update example 2020-03-01 21:17:50 -08:00
Kelly Brazil
d9de11ef1d add another who example 2020-03-01 21:16:57 -08:00
Kelly Brazil
0ceda97d09 who parser tests 2020-03-01 19:03:27 -08:00
Kelly Brazil
d0dec92ba8 add who test fixtures 2020-03-01 18:57:51 -08:00
Kelly Brazil
d420c008d8 fix for pts lines with no user info 2020-03-01 17:52:14 -08:00
Kelly Brazil
f0b32db433 who doc update 2020-03-01 17:39:02 -08:00
Kelly Brazil
bc838eda59 fix output for non-extended 2020-03-01 17:38:51 -08:00
Kelly Brazil
afe55b6af0 add who parser 2020-03-01 17:07:28 -08:00
Kelly Brazil
dd3a3ac302 doc update and process pid integers 2020-03-01 17:04:06 -08:00
Kelly Brazil
f9982a7947 fixes for from and comment fields 2020-03-01 16:49:52 -08:00
Kelly Brazil
07c1be9e9a add who command parser 2020-03-01 16:30:04 -08:00
Kelly Brazil
f832b88755 add passwd and shadow tests 2020-03-01 10:17:47 -08:00
Kelly Brazil
0fac757efc add passwd and shadow parsers 2020-02-29 12:25:41 -08:00
Kelly Brazil
fc15742065 passwd and shadow test fixtures 2020-02-29 12:25:22 -08:00
Kelly Brazil
6f2466a131 update readme with /etc/passwd and /etc/shadow file parsers 2020-02-29 11:56:12 -08:00
Kelly Brazil
4b90e22f0a doc update 2020-02-29 11:50:46 -08:00
Kelly Brazil
c493568785 doc fix 2020-02-29 11:46:38 -08:00
Kelly Brazil
1cdf004b77 add /etc/shadow parser 2020-02-29 11:46:24 -08:00
Kelly Brazil
a4ea504261 add /etc/passwd parser 2020-02-29 11:33:14 -08:00
Kelly Brazil
4c2c234c3b add last and lastb tests 2020-02-28 15:15:24 -08:00
Kelly Brazil
3d4c0f3e89 add blkid tests 2020-02-28 14:50:29 -08:00
Kelly Brazil
52fad02903 doc update 2020-02-28 13:31:38 -08:00
Kelly Brazil
9dcabc057c support multi device udev output 2020-02-28 10:57:14 -08:00
Kelly Brazil
db8c1079dd use maxsplit=1 in case there are multiple '=' delimiters 2020-02-28 09:54:07 -08:00
Kelly Brazil
8f954673ab use shlex split for values within quotations that have spaces 2020-02-28 09:07:36 -08:00
Kelly Brazil
79522d1c7d doc fixes 2020-02-28 08:51:48 -08:00
Kelly Brazil
a18bf03079 use raw strings for regular expressions 2020-02-28 08:50:35 -08:00
Kelly Brazil
c02b6b5d82 doc updates 2020-02-27 21:21:19 -08:00
Kelly Brazil
f99b423284 doc update 2020-02-27 21:04:24 -08:00
Kelly Brazil
d7d9d45d4f add missing comma 2020-02-27 20:59:09 -08:00
Kelly Brazil
90065ec0cd add more integers 2020-02-27 20:57:22 -08:00
Kelly Brazil
51157ebb86 another devname fix 2020-02-27 20:49:14 -08:00
Kelly Brazil
96d95c79ca devname fix 2020-02-27 20:47:07 -08:00
Kelly Brazil
e5da34c233 check if devname key exists before renaming 2020-02-27 20:41:06 -08:00
Kelly Brazil
f09d657f77 rename devname to device 2020-02-27 20:36:19 -08:00
Kelly Brazil
0f4b0189f5 process integer values 2020-02-27 20:31:17 -08:00
Kelly Brazil
4666042abb add blkid parser 2020-02-27 20:21:02 -08:00
Kelly Brazil
027d544c2b add last and lastb parser 2020-02-27 16:08:56 -08:00
Kelly Brazil
f1967d0138 system_boot fix 2020-02-27 16:08:39 -08:00
Kelly Brazil
c1d896027d fix system_boot tty 2020-02-27 15:58:12 -08:00
Kelly Brazil
5c2d2a6618 process function and docs 2020-02-27 15:44:36 -08:00
Kelly Brazil
997b269b0b btmp fix 2020-02-27 15:26:09 -08:00
Kelly Brazil
61257e7525 add last and lastb parser 2020-02-27 15:14:43 -08:00
Kelly Brazil
53ee2c3631 Merge pull request #29 from kellyjonbrazil/dev
Dev v1.7.5
2020-02-27 10:59:14 -08:00
Kelly Brazil
8bfa0bddec version bump to 1.7.5 2020-02-27 10:50:05 -08:00
Kelly Brazil
ad61e6bc81 add ls tests for filenames with newline characters 2020-02-27 10:48:09 -08:00
Kelly Brazil
873b5ba8ac move examples to bottom 2020-02-27 09:36:57 -08:00
Kelly Brazil
6ae50054e2 readme update 2020-02-24 20:30:44 -08:00
Kelly Brazil
22a35f41bf move variables to top 2020-02-24 17:50:56 -08:00
Kelly Brazil
961696c963 add a warning if newlines are detected in naked ls 2020-02-24 17:47:31 -08:00
Kelly Brazil
c7b7f1a5dc fix for files with newlines in naked ls 2020-02-24 17:24:56 -08:00
Kelly Brazil
b5a0d650b1 ls output with newlines 2020-02-24 17:01:33 -08:00
Kelly Brazil
573b279464 fixup for filenames that start with a newline character 2020-02-24 17:01:12 -08:00
Kelly Brazil
116e07f161 fixes for multiple consecutive newlines and trailing newlines in filenames 2020-02-24 16:38:29 -08:00
Kelly Brazil
964868c8af add support for newlines in filenames (only with ls -l) 2020-02-24 15:19:43 -08:00
Kelly Brazil
c8dac32df8 readme update 2020-02-24 13:05:35 -08:00
Kelly Brazil
72a0016bd8 use link to anchor for Parsers 2020-02-20 15:38:45 -08:00
Kelly Brazil
2ad3167434 update doc url 2020-02-19 07:12:43 -08:00
262 changed files with 35444 additions and 655 deletions

31
.github/workflows/pythonapp.yml vendored Normal file
View File

@@ -0,0 +1,31 @@
name: Tests
on:
push:
paths:
- "**/*.py"
pull_request:
paths:
- "**/*.py"
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-latest, ubuntu-latest, windows-latest]
python-version: [3.6, 3.7, 3.8]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Test with unittest
run: |
python -m unittest discover tests

1
.gitignore vendored
View File

@@ -4,3 +4,4 @@ dist/
build/
*.egg-info/
jc/parsers.old/
.github/

View File

@@ -1 +0,0 @@
graft tests/fixtures

577
README.md
View File

@@ -1,7 +1,10 @@
![Tests](https://github.com/kellyjonbrazil/jc/workflows/Tests/badge.svg?branch=master)
![Pypi](https://img.shields.io/pypi/v/jc.svg)
# JC
JSON CLI output utility
`jc` is used to JSONify the output of many standard linux cli tools and file types for easier parsing in scripts. See the **Parsers** section for supported commands.
`jc` is used to JSONify the output of many standard linux cli tools and file types for easier parsing in scripts. See the [**Parsers**](#parsers) section for supported commands and file types.
This allows further command line processing of output with tools like `jq` simply by piping commands:
```
@@ -29,7 +32,7 @@ $ jc ls -l /usr/bin | jq '.[] | select(.size > 50000000)'
"date": "Aug 14 19:41"
}
```
The `jc` parsers can also be used as python modules. In this case the output will be a python dictionary instead of JSON:
The `jc` parsers can also be used as python modules. In this case the output will be a python dictionary, or list of dictionaries, instead of JSON:
```
>>> import jc.parsers.ls
>>>
@@ -59,24 +62,33 @@ Two representations of the data are possible. The default representation uses a
To access the raw, pre-processed JSON, use the `-r` cli option or the `raw=True` function parameter in `parse()`.
Schemas for each parser can be found in the [`docs/parsers`](https://github.com/kellyjonbrazil/jc/tree/dev/docs/parsers) folder.
Schemas for each parser can be found in the [`docs/parsers`](https://github.com/kellyjonbrazil/jc/tree/master/docs/parsers) folder.
Release notes can be found [here](https://blog.kellybrazil.com/category/jc-news/).
For more information on the motivations for this project, please see my [blog post](https://blog.kellybrazil.com/2019/11/26/bringing-the-unix-philosophy-to-the-21st-century/).
## Installation
There are several ways to get `jc`. You can install via `pip`, `brew`, DEB or RPM packages, or by downloading the correct binary for your architecture and running it anywhere on your filesystem.
### Pip (macOS, linux, unix, Windows)
```
$ pip3 install --upgrade jc
```
### Brew (macOS)
```
$ brew install jc
```
### Packages and Binaries
Please see https://kellyjonbrazil.github.io/jc-packaging/ for details.
## Usage
`jc` accepts piped input from `STDIN` and outputs a JSON representation of the previous command's output to `STDOUT`.
```
COMMAND | jc PARSER [OPTIONS]
```
or
```
COMMAND | jc [OPTIONS] PARSER
```
Alternatively, the "magic" syntax can be used by prepending `jc` to the command to be converted. Options can be passed to `jc` immediately before the command is given. (Note: command aliases are not supported)
```
jc [OPTIONS] COMMAND
@@ -84,15 +96,22 @@ jc [OPTIONS] COMMAND
The JSON output can be compact (default) or pretty formatted with the `-p` option.
### Parsers
- `--airport` enables the `airport -I` command parser (OSX)
- `--airport-s` enables the `airport -s` command parser (OSX)
- `--arp` enables the `arp` command parser
- `--blkid` enables the `blkid` command parser
- `--crontab` enables the `crontab` command and file parser
- `--crontab-u` enables the `crontab` file parser with user support
- `--csv` enables the `CSV` file parser
- `--df` enables the `df` command parser
- `--dig` enables the `dig` command parser
- `--du` enables the `du` command parser
- `--env` enables the `env` command parser
- `--file` enables the `file` command parser
- `--free` enables the `free` command parser
- `--fstab` enables the `/etc/fstab` file parser
- `--group` enables the `/etc/group` file parser
- `--gshadow` enables the `/etc/gshadow` file parser
- `--history` enables the `history` command parser
- `--hosts` enables the `/etc/hosts` file parser
- `--id` enables the `id` command parser
@@ -100,36 +119,147 @@ The JSON output can be compact (default) or pretty formatted with the `-p` optio
- `--ini` enables the `INI` file parser
- `--iptables` enables the `iptables` command parser
- `--jobs` enables the `jobs` command parser
- `--last` enables the `last` and `lastb` command parser
- `--ls` enables the `ls` command parser
- `--lsblk` enables the `lsblk` command parser
- `--lsmod` enables the `lsmod` command parser
- `--lsof` enables the `lsof` command parser
- `--mount` enables the `mount` command parser
- `--netstat` enables the `netstat` command parser
- `--ntpq` enables the `ntpq -p` command parser
- `--passwd` enables the `/etc/passwd` file parser
- `--pip-list` enables the `pip list` command parser
- `--pip-show` enables the `pip show` command parser
- `--ps` enables the `ps` command parser
- `--route` enables the `route` command parser
- `--shadow` enables the `/etc/shadow` file parser
- `--ss` enables the `ss` command parser
- `--stat` enables the `stat` command parser
- `--systemctl` enables the `systemctl` command parser
- `--systemctl-lj` enables the `systemctl list-jobs` command parser
- `--systemctl-ls` enables the `systemctl list-sockets` command parser
- `--systemctl-luf` enables the `systemctl list-unit-files` command parser
- `--timedatectl` enables the `timedatectl status` command parser
- `--uname` enables the `uname -a` command parser
- `--uptime` enables the `uptime` command parser
- `--w` enables the `w` command parser
- `--who` enables the `who` command parser
- `--xml` enables the `XML` file parser
- `--yaml` enables the `YAML` file parser
### Options
- `-a` about `jc`. Prints information about `jc` and the parsers (in JSON, of course!)
- `-d` debug mode. Prints trace messages if parsing issues encountered
- `-m` monochrome JSON output
- `-p` pretty format the JSON output
- `-q` quiet mode. Suppresses warning messages
- `-r` raw output. Provides a more literal JSON output with all values as text and no additional sematic processing
- `-r` raw output. Provides a more literal JSON output with all values as strings and no additional sematic processing
### Setting Custom Colors via Environment Variable
You can specify custom colors via the `JC_COLORS` environment variable. The `JC_COLORS` environment variable takes four comma separated string values in the following format:
```
JC_COLORS=<keyname_color>,<keyword_color>,<number_color>,<string_color>
```
Where colors are: `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `gray`, `brightblack`, `brightred`, `brightgreen`, `brightyellow`, `brightblue`, `brightmagenta`, `brightcyan`, `white`, or `default`
For example, to set to the default colors:
```
JC_COLORS=blue,brightblack,magenta,green
```
or
```
JC_COLORS=default,default,default,default
```
## Contributions
Feel free to add/improve code or parsers! You can use the [`jc/parsers/foo.py`](https://github.com/kellyjonbrazil/jc/blob/master/jc/parsers/foo.py) parser as a template and submit your parser with a pull request.
## Compatibility
Some parsers like `ls`, `ps`, `dig`, etc. will work on any platform. Other parsers that are platform-specific will generate a warning message if they are used on an unsupported platform. To see all parser information, including compatibility, run `jc -ap`.
You may still use a parser on an unsupported platform - for example, you may want to parse a file with linux `lsof` output on an OSX laptop. In that case you can suppress the warning message with the `-q` cli option or the `quiet=True` function parameter in `parse()`:
```
$ cat lsof.out | jc --lsof -q
```
Tested on:
- Centos 7.7
- Ubuntu 18.4
- OSX 10.11.6
- OSX 10.14.6
## Acknowledgments
- CI automation and code optimizations from https://github.com/philippeitis
- `ifconfig-parser` module from https://github.com/KnightWhoSayNi/ifconfig-parser
- `xmltodict` module from https://github.com/martinblech/xmltodict by Martín Blech
- `ruamel.yaml` library from https://pypi.org/project/ruamel.yaml by Anthon van der Neut
- Parsing code from Conor Heine at https://gist.github.com/cahna/43a1a3ff4d075bcd71f9d7120037a501 adapted for some parsers
- Excellent constructive feedback from Ilya Sher (https://github.com/ilyash-b)
## Examples
### airport -I
```
$ airport -I | jc --airport -p # or: jc -p airport -I
{
"agrctlrssi": -66,
"agrextrssi": 0,
"agrctlnoise": -90,
"agrextnoise": 0,
"state": "running",
"op_mode": "station",
"lasttxrate": 195,
"maxrate": 867,
"lastassocstatus": 0,
"802_11_auth": "open",
"link_auth": "wpa2-psk",
"bssid": "3c:37:86:15:ad:f9",
"ssid": "SnazzleDazzle",
"mcs": 0,
"channel": "48,80"
}
```
### airport -s
```
$ airport -s | jc --airport-s -p # or: jc -p airport -s
[
{
"ssid": "DIRECT-4A-HP OfficeJet 3830",
"bssid": "00:67:eb:2a:a7:3b",
"rssi": -90,
"channel": "6",
"ht": true,
"cc": "--",
"security": [
"WPA2(PSK/AES/AES)"
]
},
{
"ssid": "Latitude38",
"bssid": "c0:ff:d5:d2:7a:f3",
"rssi": -85,
"channel": "11",
"ht": true,
"cc": "US",
"security": [
"WPA2(PSK/AES/AES)"
]
},
{
"ssid": "xfinitywifi",
"bssid": "6e:e3:0e:b8:45:99",
"rssi": -83,
"channel": "11",
"ht": true,
"cc": "US",
"security": [
"NONE"
]
},
...
]
```
### arp
```
$ arp | jc --arp -p # or: jc -p arp
@@ -183,6 +313,53 @@ $ arp -a | jc --arp -p # or: jc -p arp -a
}
]
```
### blkid
```
$ blkid | jc --blkid -p # or: jc -p blkid
[
{
"device": "/dev/sda1",
"uuid": "05d927ab-5875-49e4-ada1-7f46cb32c932",
"type": "xfs"
},
{
"device": "/dev/sda2",
"uuid": "3klkIj-w1kk-DkJi-0XBJ-y3i7-i2Ac-vHqWBM",
"type": "LVM2_member"
},
{
"device": "/dev/mapper/centos-root",
"uuid": "07d718ff-950c-4e5b-98f0-42a1147c77d9",
"type": "xfs"
},
{
"device": "/dev/mapper/centos-swap",
"uuid": "615eb89a-bcbf-46fd-80e3-c483ff5c931f",
"type": "swap"
}
]
```
```
$ sudo blkid -o udev -ip /dev/sda2 | jc --blkid -p # or: sudo jc -p blkid -o udev -ip /dev/sda2
[
{
"id_fs_uuid": "3klkIj-w1kk-DkJi-0XBJ-y3i7-i2Ac-vHqWBM",
"id_fs_uuid_enc": "3klkIj-w1kk-DkJi-0XBJ-y3i7-i2Ac-vHqWBM",
"id_fs_version": "LVM2\x20001",
"id_fs_type": "LVM2_member",
"id_fs_usage": "raid",
"id_iolimit_minimum_io_size": 512,
"id_iolimit_physical_sector_size": 512,
"id_iolimit_logical_sector_size": 512,
"id_part_entry_scheme": "dos",
"id_part_entry_type": "0x8e",
"id_part_entry_number": 2,
"id_part_entry_offset": 2099200,
"id_part_entry_size": 39843840,
"id_part_entry_disk": "8:0"
}
]
```
### crontab
```
$ cat /etc/crontab | jc --crontab -p # or: jc -p crontab -l
@@ -330,6 +507,53 @@ $ cat /etc/crontab | jc --crontab-u -p
]
}
```
### CSV files
```
$ cat homes.csv
"Sell", "List", "Living", "Rooms", "Beds", "Baths", "Age", "Acres", "Taxes"
142, 160, 28, 10, 5, 3, 60, 0.28, 3167
175, 180, 18, 8, 4, 1, 12, 0.43, 4033
129, 132, 13, 6, 3, 1, 41, 0.33, 1471
...
$ cat homes.csv | jc --csv -p
[
{
"Sell": "142",
"List": "160",
"Living": "28",
"Rooms": "10",
"Beds": "5",
"Baths": "3",
"Age": "60",
"Acres": "0.28",
"Taxes": "3167"
},
{
"Sell": "175",
"List": "180",
"Living": "18",
"Rooms": "8",
"Beds": "4",
"Baths": "1",
"Age": "12",
"Acres": "0.43",
"Taxes": "4033"
},
{
"Sell": "129",
"List": "132",
"Living": "13",
"Rooms": "6",
"Beds": "3",
"Baths": "1",
"Age": "41",
"Acres": "0.33",
"Taxes": "1471"
},
...
]
```
### df
```
$ df | jc --df -p # or: jc -p df
@@ -569,6 +793,41 @@ $ env | jc --env -p # or: jc -p env
...
]
```
### file
```
$ file * | jc --file -p # or: jc -p file *
[
{
"filename": "Applications",
"type": "directory"
},
{
"filename": "another file with spaces",
"type": "empty"
},
{
"filename": "argstest.py",
"type": "Python script text executable, ASCII text"
},
{
"filename": "blkid-p.out",
"type": "ASCII text"
},
{
"filename": "blkid-pi.out",
"type": "ASCII text, with very long lines"
},
{
"filename": "cd_catalog.xml",
"type": "XML 1.0 document text, ASCII text, with CRLF line terminators"
},
{
"filename": "centosserial.sh",
"type": "Bourne-Again shell script text executable, UTF-8 Unicode text"
},
...
]
```
### free
```
$ free | jc --free -p # or: jc -p free
@@ -620,6 +879,68 @@ $ cat /etc/fstab | jc --fstab -p
}
]
```
### /etc/group file
```
$ cat /etc/group | jc --group -p
[
{
"group_name": "nobody",
"password": "*",
"gid": -2,
"members": []
},
{
"group_name": "nogroup",
"password": "*",
"gid": -1,
"members": []
},
{
"group_name": "wheel",
"password": "*",
"gid": 0,
"members": [
"root"
]
},
{
"group_name": "certusers",
"password": "*",
"gid": 29,
"members": [
"root",
"_jabber",
"_postfix",
"_cyrus",
"_calendar",
"_dovecot"
]
},
...
]
```
### /etc/gshadow file
```
$ cat /etc/gshadow | jc --gshadow -p
[
{
"group_name": "root",
"password": "*",
"administrators": [],
"members": []
},
{
"group_name": "adm",
"password": "*",
"administrators": [],
"members": [
"syslog",
"joeuser"
]
},
...
]
```
### history
```
$ history | jc --history -p
@@ -920,6 +1241,36 @@ $ jobs -l | jc --jobs -p # or: jc -p jobs
}
]
```
### last and lastb
```
$ last | jc --last -p # or: jc -p last
[
{
"user": "joeuser",
"tty": "ttys002",
"hostname": null,
"login": "Thu Feb 27 14:31",
"logout": "still logged in"
},
{
"user": "joeuser",
"tty": "ttys003",
"hostname": null,
"login": "Thu Feb 27 10:38",
"logout": "10:38",
"duration": "00:00"
},
{
"user": "joeuser",
"tty": "ttys003",
"hostname": null,
"login": "Thu Feb 27 10:18",
"logout": "10:18",
"duration": "00:00"
},
...
]
```
### ls
```
$ ls -l /usr/bin | jc --ls -p # or: jc -p ls -l /usr/bin
@@ -1266,6 +1617,72 @@ $ sudo netstat -apee | jc --netstat -p # or: sudo jc -p netstat -apee
...
]
```
### ntpq
```
$ ntpq -p | jc --ntpq -p # or: jc -p ntpq -p
[
{
"remote": "44.190.6.254",
"refid": "127.67.113.92",
"st": 2,
"t": "u",
"when": 1,
"poll": 64,
"reach": 1,
"delay": 23.399,
"offset": -2.805,
"jitter": 2.131,
"state": null
},
{
"remote": "mirror1.sjc02.s",
"refid": "216.218.254.202",
"st": 2,
"t": "u",
"when": 2,
"poll": 64,
"reach": 1,
"delay": 29.325,
"offset": 1.044,
"jitter": 4.069,
"state": null
}
]
```
### /etc/passwd file
```
$ cat /etc/passwd | jc --passwd -p
[
{
"username": "nobody",
"password": "*",
"uid": -2,
"gid": -2,
"comment": "Unprivileged User",
"home": "/var/empty",
"shell": "/usr/bin/false"
},
{
"username": "root",
"password": "*",
"uid": 0,
"gid": 0,
"comment": "System Administrator",
"home": "/var/root",
"shell": "/bin/sh"
},
{
"username": "daemon",
"password": "*",
"uid": 1,
"gid": 1,
"comment": "System Services",
"home": "/var/root",
"shell": "/usr/bin/false"
},
...
]
```
### pip list
```
$ pip list | jc --pip-list -p # or: jc -p pip list # or: jc -p pip3 list
@@ -1443,6 +1860,43 @@ $ route -ee | jc --route -p # or: jc -p route -ee
}
]
```
### /etc/shadow file
```
$ sudo cat /etc/shadow | jc --shadow -p
[
{
"username": "root",
"password": "*",
"last_changed": 18113,
"minimum": 0,
"maximum": 99999,
"warn": 7,
"inactive": null,
"expire": null
},
{
"username": "daemon",
"password": "*",
"last_changed": 18113,
"minimum": 0,
"maximum": 99999,
"warn": 7,
"inactive": null,
"expire": null
},
{
"username": "bin",
"password": "*",
"last_changed": 18113,
"minimum": 0,
"maximum": 99999,
"warn": 7,
"inactive": null,
"expire": null
},
...
]
```
### ss
```
$ sudo ss -a | jc --ss -p # or: sudo jc -p ss -a
@@ -1702,6 +2156,20 @@ $ systemctl list-unit-files | jc --systemctl-luf -p # or: jc -p system
...
]
```
### timedatectl status
```
$ timedatectl | jc --timedatectl -p # or: jc -p timedatectl
{
"local_time": "Tue 2020-03-10 17:53:21 PDT",
"universal_time": "Wed 2020-03-11 00:53:21 UTC",
"rtc_time": "Wed 2020-03-11 00:53:21",
"time_zone": "America/Los_Angeles (PDT, -0700)",
"ntp_enabled": true,
"ntp_synchronized": true,
"rtc_in_local_tz": false,
"dst_active": true
}
```
### uname -a
```
$ uname -a | jc --uname -p # or: jc -p uname -a
@@ -1764,6 +2232,67 @@ $ w | jc --w -p # or: jc -p w
}
]
```
### who
```
$ who | jc --who -p # or: jc -p who
[
{
"user": "joeuser",
"tty": "ttyS0",
"time": "2020-03-02 02:52"
},
{
"user": "joeuser",
"tty": "pts/0",
"time": "2020-03-02 05:15",
"from": "192.168.71.1"
}
]
```
```
$ who -a | jc --who -p # or: jc -p who -a
[
{
"event": "reboot",
"time": "Feb 7 23:31",
"pid": 1
},
{
"user": "joeuser",
"writeable_tty": "-",
"tty": "console",
"time": "Feb 7 23:32",
"idle": "old",
"pid": 105
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys000",
"time": "Feb 13 16:44",
"idle": ".",
"pid": 51217,
"comment": "term=0 exit=0"
},
{
"user": "joeuser",
"writeable_tty": "?",
"tty": "ttys003",
"time": "Feb 28 08:59",
"idle": "01:36",
"pid": 41402
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys004",
"time": "Mar 1 16:35",
"idle": ".",
"pid": 15679,
"from": "192.168.1.5"
}
]
```
### XML files
```
$ cat cd_catalog.xml
@@ -1867,34 +2396,4 @@ $ cat istio.yaml | jc --yaml -p
}
}
]
```
## TODO
Future parsers:
- /proc files
- /sys files
## Contributions
Feel free to add/improve code or parsers! You can use the `jc/parsers/foo.py` parser as a template and submit your parser with a pull request.
## Compatibility
Some parsers like `ls`, `ps`, `dig`, etc. will work on any platform. Other parsers that are platform-specific will generate a warning message if they are used on an unsupported platform. To see all parser information, including compatibility, run `jc -ap`.
You may still use a parser on an unsupported platform - for example, you may want to parse a file with linux `lsof` output on an OSX laptop. In that case you can suppress the warning message with the `-q` cli option or the `quiet=True` function parameter in `parse()`:
```
$ cat lsof.out | jc --lsof -q
```
Tested on:
- Centos 7.7
- Ubuntu 18.4
- OSX 10.11.6
- OSX 10.14.6
## Acknowledgments
- `ifconfig-parser` module from https://github.com/KnightWhoSayNi/ifconfig-parser
- `xmltodict` module from https://github.com/martinblech/xmltodict by Martín Blech
- `ruamel.yaml` library from https://pypi.org/project/ruamel.yaml by Anthon van der Neut
- Parsing code from Conor Heine at https://gist.github.com/cahna/43a1a3ff4d075bcd71f9d7120037a501 adapted for some parsers
- Excellent constructive feedback from Ilya Sher (https://github.com/ilyash-b)
```

View File

@@ -1,5 +1,70 @@
jc changelog
20200508 v1.10.8
- Add license file to dist for Fedora RPM packaging requirements
- Remove tests from package to keep from polluting the global site-packages
20200501 v1.10.7
- Requirements modifications for Fedora RPM packaging requirements
20200420 v1.10.6
- Remove homebrew shim references from du osx tests
20200414 v1.10.5
- Minor change of using sys.exit(0) instead of exit()
20200412 v1.10.4
- Add color customization via JC_COLORS env variable
20200409 v1.10.3
- Fix break on pipe error
20200409 v1.10.2
- Change colors to ansi and match jello colors
20200402 v1.10.1
- Code cleanup
20200402 v1.10.0
- Add color output by default when not piping data to another program
- Add -m option for monochrome output
20200326 v1.9.3
- Add axfr support for dig command parser
20200312 v1.9.2
- Updated arp parser to fix OSX detection for some edge cases
20200312 v1.9.1
- Updated file command parser to make filename splitting more robust
20200311 v1.9.0
- Added ntpq command parser
- Added timedatectl status command parser
- Added airport -I and airport -s command parser
- Added file command parser
- Optimized history command parser by https://github.com/philippeitis
- Magic syntax fix for certain edge cases
20200308 v1.8.1
- CLI optimizations by https://github.com/philippeitis
- Refactored magic syntax function and added tests (https://github.com/philippeitis)
- Github actions for CI testing on multiple platforms by https://github.com/philippeitis
- Updated ls parser to fix parsing error in OSX with -lR when there are empty folders
20200303 v1.8.0
- Added blkid command parser
- Added last and lastb command parser
- Added who command parser
- Added CSV file parser
- Added /etc/passwd file parser
- Added /etc/shadow file parser
- Added /etc/group file parser
- Added /etc/gshadow file parser
20200227 v1.7.5
- Updated ls parser to support filenames with newline characters
20200219 v1.7.4
- Updated ls parser to support multiple directories, globbing, and -R (recursive)

View File

@@ -4,15 +4,22 @@
cd jc
pydocmd simple jc+ > ../docs/readme.md
pydocmd simple utils+ > ../docs/utils.md
pydocmd simple jc.parsers.airport+ > ../docs/parsers/airport.md
pydocmd simple jc.parsers.airport_s+ > ../docs/parsers/airport_s.md
pydocmd simple jc.parsers.arp+ > ../docs/parsers/arp.md
pydocmd simple jc.parsers.blkid+ > ../docs/parsers/blkid.md
pydocmd simple jc.parsers.crontab+ > ../docs/parsers/crontab.md
pydocmd simple jc.parsers.crontab_u+ > ../docs/parsers/crontab_u.md
pydocmd simple jc.parsers.csv+ > ../docs/parsers/csv.md
pydocmd simple jc.parsers.df+ > ../docs/parsers/df.md
pydocmd simple jc.parsers.dig+ > ../docs/parsers/dig.md
pydocmd simple jc.parsers.du+ > ../docs/parsers/du.md
pydocmd simple jc.parsers.env+ > ../docs/parsers/env.md
pydocmd simple jc.parsers.file+ > ../docs/parsers/file.md
pydocmd simple jc.parsers.free+ > ../docs/parsers/free.md
pydocmd simple jc.parsers.fstab+ > ../docs/parsers/fstab.md
pydocmd simple jc.parsers.group+ > ../docs/parsers/group.md
pydocmd simple jc.parsers.gshadow+ > ../docs/parsers/gshadow.md
pydocmd simple jc.parsers.history+ > ../docs/parsers/history.md
pydocmd simple jc.parsers.hosts+ > ../docs/parsers/hosts.md
pydocmd simple jc.parsers.id+ > ../docs/parsers/id.md
@@ -20,24 +27,30 @@ pydocmd simple jc.parsers.ifconfig+ > ../docs/parsers/ifconfig.md
pydocmd simple jc.parsers.ini+ > ../docs/parsers/ini.md
pydocmd simple jc.parsers.iptables+ > ../docs/parsers/iptables.md
pydocmd simple jc.parsers.jobs+ > ../docs/parsers/jobs.md
pydocmd simple jc.parsers.last+ > ../docs/parsers/last.md
pydocmd simple jc.parsers.ls+ > ../docs/parsers/ls.md
pydocmd simple jc.parsers.lsblk+ > ../docs/parsers/lsblk.md
pydocmd simple jc.parsers.lsmod+ > ../docs/parsers/lsmod.md
pydocmd simple jc.parsers.lsof+ > ../docs/parsers/lsof.md
pydocmd simple jc.parsers.mount+ > ../docs/parsers/mount.md
pydocmd simple jc.parsers.netstat+ > ../docs/parsers/netstat.md
pydocmd simple jc.parsers.ntpq+ > ../docs/parsers/ntpq.md
pydocmd simple jc.parsers.passwd+ > ../docs/parsers/passwd.md
pydocmd simple jc.parsers.pip_list+ > ../docs/parsers/pip_list.md
pydocmd simple jc.parsers.pip_show+ > ../docs/parsers/pip_show.md
pydocmd simple jc.parsers.ps+ > ../docs/parsers/ps.md
pydocmd simple jc.parsers.route+ > ../docs/parsers/route.md
pydocmd simple jc.parsers.shadow+ > ../docs/parsers/shadow.md
pydocmd simple jc.parsers.ss+ > ../docs/parsers/ss.md
pydocmd simple jc.parsers.stat+ > ../docs/parsers/stat.md
pydocmd simple jc.parsers.systemctl+ > ../docs/parsers/systemctl.md
pydocmd simple jc.parsers.systemctl_lj+ > ../docs/parsers/systemctl_lj.md
pydocmd simple jc.parsers.systemctl_ls+ > ../docs/parsers/systemctl_ls.md
pydocmd simple jc.parsers.systemctl_luf+ > ../docs/parsers/systemctl_luf.md
pydocmd simple jc.parsers.timedatectl+ > ../docs/parsers/timedatectl.md
pydocmd simple jc.parsers.uname+ > ../docs/parsers/uname.md
pydocmd simple jc.parsers.uptime+ > ../docs/parsers/uptime.md
pydocmd simple jc.parsers.w+ > ../docs/parsers/w.md
pydocmd simple jc.parsers.who+ > ../docs/parsers/who.md
pydocmd simple jc.parsers.xml+ > ../docs/parsers/xml.md
pydocmd simple jc.parsers.yaml+ > ../docs/parsers/yaml.md

109
docs/parsers/airport.md Normal file
View File

@@ -0,0 +1,109 @@
# jc.parsers.airport
jc - JSON CLI output utility airport -I Parser
Usage:
specify --airport as the first argument if the piped input is coming from airport -I (OSX)
This program can be found at:
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport
Compatibility:
'darwin'
Examples:
$ airport -I | jc --airport -p
{
"agrctlrssi": -66,
"agrextrssi": 0,
"agrctlnoise": -90,
"agrextnoise": 0,
"state": "running",
"op_mode": "station",
"lasttxrate": 195,
"maxrate": 867,
"lastassocstatus": 0,
"802_11_auth": "open",
"link_auth": "wpa2-psk",
"bssid": "3c:37:86:15:ad:f9",
"ssid": "SnazzleDazzle",
"mcs": 0,
"channel": "48,80"
}
$ airport -I | jc --airport -p -r
{
"agrctlrssi": "-66",
"agrextrssi": "0",
"agrctlnoise": "-90",
"agrextnoise": "0",
"state": "running",
"op_mode": "station",
"lasttxrate": "195",
"maxrate": "867",
"lastassocstatus": "0",
"802_11_auth": "open",
"link_auth": "wpa2-psk",
"bssid": "3c:37:86:15:ad:f9",
"ssid": "SnazzleDazzle",
"mcs": "0",
"channel": "48,80"
}
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
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:
{
"agrctlrssi": integer,
"agrextrssi": integer,
"agrctlnoise": integer,
"agrextnoise": integer,
"state": string,
"op_mode": string,
"lasttxrate": integer,
"maxrate": integer,
"lastassocstatus": integer,
"802_11_auth": string,
"link_auth": string,
"bssid": string,
"ssid": string,
"mcs": integer,
"channel": string
}
## parse
```python
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.

136
docs/parsers/airport_s.md Normal file
View File

@@ -0,0 +1,136 @@
# jc.parsers.airport_s
jc - JSON CLI output utility airport -s Parser
Usage:
specify --airport as the first argument if the piped input is coming from airport -s (OSX)
This program can be found at:
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport
Compatibility:
'darwin'
Examples:
$ airport -s | jc --airport-s -p
[
{
"ssid": "DIRECT-4A-HP OfficeJet 3830",
"bssid": "00:67:eb:2a:a7:3b",
"rssi": -90,
"channel": "6",
"ht": true,
"cc": "--",
"security": [
"WPA2(PSK/AES/AES)"
]
},
{
"ssid": "Latitude38",
"bssid": "c0:ff:d5:d2:7a:f3",
"rssi": -85,
"channel": "11",
"ht": true,
"cc": "US",
"security": [
"WPA2(PSK/AES/AES)"
]
},
{
"ssid": "xfinitywifi",
"bssid": "6e:e3:0e:b8:45:99",
"rssi": -83,
"channel": "11",
"ht": true,
"cc": "US",
"security": [
"NONE"
]
},
...
]
$ airport -s | jc --airport -p -r
[
{
"ssid": "DIRECT-F3-HP ENVY 5660 series",
"bssid": "b0:5a:da:6f:0a:d4",
"rssi": "-93",
"channel": "1",
"ht": "Y",
"cc": "--",
"security": "WPA2(PSK/AES/AES)"
},
{
"ssid": "YouAreInfected-5",
"bssid": "5c:e3:0e:c2:85:da",
"rssi": "-85",
"channel": "36",
"ht": "Y",
"cc": "US",
"security": "WPA(PSK/AES,TKIP/TKIP) WPA2(PSK/AES,TKIP/TKIP)"
},
{
"ssid": "YuanFamily",
"bssid": "5c:e3:0e:b8:5f:9a",
"rssi": "-84",
"channel": "11",
"ht": "Y",
"cc": "US",
"security": "WPA(PSK/AES,TKIP/TKIP) WPA2(PSK/AES,TKIP/TKIP)"
},
...
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"ssid": string,
"bssid": string,
"rssi": integer,
"channel": string,
"ht": boolean,
"cc": string,
"security": [
string,
]
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

148
docs/parsers/blkid.md Normal file
View File

@@ -0,0 +1,148 @@
# jc.parsers.blkid
jc - JSON CLI output utility blkid Parser
Usage:
specify --blkid as the first argument if the piped input is coming from blkid
Compatibility:
'linux'
Examples:
$ blkid | jc --blkid -p
[
{
"device": "/dev/sda1",
"uuid": "05d927ab-5875-49e4-ada1-7f46cb32c932",
"type": "xfs"
},
{
"device": "/dev/sda2",
"uuid": "3klkIj-w1kk-DkJi-0XBJ-y3i7-i2Ac-vHqWBM",
"type": "LVM2_member"
},
{
"device": "/dev/mapper/centos-root",
"uuid": "07d718ff-950c-4e5b-98f0-42a1147c77d9",
"type": "xfs"
},
{
"device": "/dev/mapper/centos-swap",
"uuid": "615eb89a-bcbf-46fd-80e3-c483ff5c931f",
"type": "swap"
}
]
$ sudo blkid -o udev -ip /dev/sda2 | jc --blkid -p
[
{
"id_fs_uuid": "3klkIj-w1kk-DkJi-0XBJ-y3i7-i2Ac-vHqWBM",
"id_fs_uuid_enc": "3klkIj-w1kk-DkJi-0XBJ-y3i7-i2Ac-vHqWBM",
"id_fs_version": "LVM2\x20001",
"id_fs_type": "LVM2_member",
"id_fs_usage": "raid",
"id_iolimit_minimum_io_size": 512,
"id_iolimit_physical_sector_size": 512,
"id_iolimit_logical_sector_size": 512,
"id_part_entry_scheme": "dos",
"id_part_entry_type": "0x8e",
"id_part_entry_number": 2,
"id_part_entry_offset": 2099200,
"id_part_entry_size": 39843840,
"id_part_entry_disk": "8:0"
}
]
$ sudo blkid -ip /dev/sda1 | jc --blkid -p -r
[
{
"devname": "/dev/sda1",
"uuid": "05d927bb-5875-49e3-ada1-7f46cb31c932",
"type": "xfs",
"usage": "filesystem",
"minimum_io_size": "512",
"physical_sector_size": "512",
"logical_sector_size": "512",
"part_entry_scheme": "dos",
"part_entry_type": "0x83",
"part_entry_flags": "0x80",
"part_entry_number": "1",
"part_entry_offset": "2048",
"part_entry_size": "2097152",
"part_entry_disk": "8:0"
}
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"device": string,
"uuid": string,
"type": string,
"usage": string,
"part_entry_scheme": string,
"part_entry_type": string,
"part_entry_flags": string,
"part_entry_number": integer,
"part_entry_offset": integer,
"part_entry_size": integer,
"part_entry_disk": string,
"id_fs_uuid": string,
"id_fs_uuid_enc": string,
"id_fs_version": string,
"id_fs_type": string,
"id_fs_usage": string,
"id_part_entry_scheme": string,
"id_part_entry_type": string,
"id_part_entry_flags": string,
"id_part_entry_number": integer,
"id_part_entry_offset": integer,
"id_part_entry_size": integer,
"id_iolimit_minimum_io_size": integer,
"id_iolimit_physical_sector_size": integer,
"id_iolimit_logical_sector_size": integer,
"id_part_entry_disk": string,
"minimum_io_size": integer,
"physical_sector_size": integer,
"logical_sector_size": integer
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

105
docs/parsers/csv.md Normal file
View File

@@ -0,0 +1,105 @@
# jc.parsers.csv
jc - JSON CLI output utility csv Parser
Usage:
specify --csv as the first argument if the piped input is coming from a csv file.
the csv parser will attempt to automatically detect the delimiter character.
if the delimiter cannot be detected it will default to comma.
the first row of the file must be a header row.
Compatibility:
'linux', 'darwin', 'cygwin', 'win32', 'aix', 'freebsd'
Examples:
$ cat homes.csv
"Sell", "List", "Living", "Rooms", "Beds", "Baths", "Age", "Acres", "Taxes"
142, 160, 28, 10, 5, 3, 60, 0.28, 3167
175, 180, 18, 8, 4, 1, 12, 0.43, 4033
129, 132, 13, 6, 3, 1, 41, 0.33, 1471
...
$ cat homes.csv | jc --csv -p
[
{
"Sell": "142",
"List": "160",
"Living": "28",
"Rooms": "10",
"Beds": "5",
"Baths": "3",
"Age": "60",
"Acres": "0.28",
"Taxes": "3167"
},
{
"Sell": "175",
"List": "180",
"Living": "18",
"Rooms": "8",
"Beds": "4",
"Baths": "1",
"Age": "12",
"Acres": "0.43",
"Taxes": "4033"
},
{
"Sell": "129",
"List": "132",
"Living": "13",
"Rooms": "6",
"Beds": "3",
"Baths": "1",
"Age": "41",
"Acres": "0.33",
"Taxes": "1471"
},
...
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Each dictionary represents a row in the csv file:
[
{
csv file converted to a Dictionary
https://docs.python.org/3/library/csv.html
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

View File

@@ -353,6 +353,15 @@ Returns:
"answer_num": integer,
"authority_num": integer,
"additional_num": integer,
"axfr": [
{
"name": string,
"class": string,
"type": string,
"ttl": integer,
"data": string
}
],
"question": {
"name": string,
"class": string,
@@ -380,6 +389,7 @@ Returns:
"server": string,
"when": string,
"rcvd": integer
"size": string
}
]

90
docs/parsers/file.md Normal file
View File

@@ -0,0 +1,90 @@
# jc.parsers.file
jc - JSON CLI output utility file command Parser
Usage:
specify --file as the first argument if the piped input is coming from file.
Compatibility:
'linux', 'aix', 'freebsd', 'darwin'
Examples:
$ file * | jc --file -p
[
{
"filename": "Applications",
"type": "directory"
},
{
"filename": "another file with spaces",
"type": "empty"
},
{
"filename": "argstest.py",
"type": "Python script text executable, ASCII text"
},
{
"filename": "blkid-p.out",
"type": "ASCII text"
},
{
"filename": "blkid-pi.out",
"type": "ASCII text, with very long lines"
},
{
"filename": "cd_catalog.xml",
"type": "XML 1.0 document text, ASCII text, with CRLF line terminators"
},
{
"filename": "centosserial.sh",
"type": "Bourne-Again shell script text executable, UTF-8 Unicode text"
},
...
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"filename": string,
"type ": string
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

141
docs/parsers/group.md Normal file
View File

@@ -0,0 +1,141 @@
# jc.parsers.group
jc - JSON CLI output utility /etc/group file Parser
Usage:
specify --group as the first argument if the piped input is coming from /etc/group
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ cat /etc/group | jc --group -p
[
{
"group_name": "nobody",
"password": "*",
"gid": -2,
"members": []
},
{
"group_name": "nogroup",
"password": "*",
"gid": -1,
"members": []
},
{
"group_name": "wheel",
"password": "*",
"gid": 0,
"members": [
"root"
]
},
{
"group_name": "certusers",
"password": "*",
"gid": 29,
"members": [
"root",
"_jabber",
"_postfix",
"_cyrus",
"_calendar",
"_dovecot"
]
},
...
]
$ cat /etc/group | jc --group -p -r
[
{
"group_name": "nobody",
"password": "*",
"gid": "-2",
"members": [
""
]
},
{
"group_name": "nogroup",
"password": "*",
"gid": "-1",
"members": [
""
]
},
{
"group_name": "wheel",
"password": "*",
"gid": "0",
"members": [
"root"
]
},
{
"group_name": "certusers",
"password": "*",
"gid": "29",
"members": [
"root",
"_jabber",
"_postfix",
"_cyrus",
"_calendar",
"_dovecot"
]
},
...
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"group_name": string,
"password": string,
"gid": integer,
"members": [
string
]
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

109
docs/parsers/gshadow.md Normal file
View File

@@ -0,0 +1,109 @@
# jc.parsers.gshadow
jc - JSON CLI output utility /etc/gshadow file Parser
Usage:
specify --gshadow as the first argument if the piped input is coming from /etc/gshadow
Compatibility:
'linux', 'aix', 'freebsd'
Examples:
$ cat /etc/gshadow | jc --gshadow -p
[
{
"group_name": "root",
"password": "*",
"administrators": [],
"members": []
},
{
"group_name": "adm",
"password": "*",
"administrators": [],
"members": [
"syslog",
"joeuser"
]
},
...
]
$ cat /etc/gshadow | jc --gshadow -p -r
[
{
"group_name": "root",
"password": "*",
"administrators": [
""
],
"members": [
""
]
},
{
"group_name": "adm",
"password": "*",
"administrators": [
""
],
"members": [
"syslog",
"joeuser"
]
},
...
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"group_name": string,
"password": string,
"administrators": [
string
],
"members": [
string
]
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

View File

@@ -147,6 +147,17 @@ Examples:
info(self, /, *args, **kwargs)
```
## IfconfigParser
```python
IfconfigParser(self, console_output)
```
## InterfaceNotFound
```python
InterfaceNotFound(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)

118
docs/parsers/last.md Normal file
View File

@@ -0,0 +1,118 @@
# jc.parsers.last
jc - JSON CLI output utility last Parser
Usage:
specify --last as the first argument if the piped input is coming from last or lastb
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ last | jc --last -p
[
{
"user": "kbrazil",
"tty": "ttys002",
"hostname": null,
"login": "Thu Feb 27 14:31",
"logout": "still logged in"
},
{
"user": "kbrazil",
"tty": "ttys003",
"hostname": null,
"login": "Thu Feb 27 10:38",
"logout": "10:38",
"duration": "00:00"
},
{
"user": "kbrazil",
"tty": "ttys003",
"hostname": null,
"login": "Thu Feb 27 10:18",
"logout": "10:18",
"duration": "00:00"
},
...
]
$ last | jc --last -p -r
[
{
"user": "kbrazil",
"tty": "ttys002",
"hostname": "-",
"login": "Thu Feb 27 14:31",
"logout": "still_logged_in"
},
{
"user": "kbrazil",
"tty": "ttys003",
"hostname": "-",
"login": "Thu Feb 27 10:38",
"logout": "10:38",
"duration": "00:00"
},
{
"user": "kbrazil",
"tty": "ttys003",
"hostname": "-",
"login": "Thu Feb 27 10:18",
"logout": "10:18",
"duration": "00:00"
},
...
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"user": string,
"tty": string,
"hostname": string,
"login": string,
"logout": string,
"duration": string
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

View File

@@ -1,17 +1,21 @@
# jc.parsers.ls
jc - JSON CLI output utility ls Parser
Note: The -l or -b option of ls should be used to correctly parse filenames that include newline characters.
Since ls does not encode newlines in filenames when outputting to a pipe it will cause jc to see
multiple files instead of a single file if -l or -b is not used.
Usage:
specify --ls as the first argument if the piped input is coming from ls
ls options supported:
- None
- laR
-lbaR
--time-style=full-iso
- h file sizes will be available in text form with -r but larger file sizes
with human readable suffixes will be converted to Null in default view
since the parser attempts to convert this field to an integer.
-h file sizes will be available in text form with -r but larger file sizes
with human readable suffixes will be converted to Null in default view
since the parser attempts to convert this field to an integer.
Compatibility:

235
docs/parsers/ntpq.md Normal file
View File

@@ -0,0 +1,235 @@
# jc.parsers.ntpq
jc - JSON CLI output utility ntpq Parser
Usage:
specify --ntpq as the first argument if the piped input is coming from ntpq -p
Compatibility:
'linux'
Examples:
$ ntpq -p | jc --ntpq -p
[
{
"remote": "44.190.6.254",
"refid": "127.67.113.92",
"st": 2,
"t": "u",
"when": 1,
"poll": 64,
"reach": 1,
"delay": 23.399,
"offset": -2.805,
"jitter": 2.131,
"state": null
},
{
"remote": "ntp.wdc1.us.lea",
"refid": "130.133.1.10",
"st": 2,
"t": "u",
"when": null,
"poll": 64,
"reach": 1,
"delay": 93.053,
"offset": -0.807,
"jitter": 2.839,
"state": null
},
{
"remote": "clock.team-cymr",
"refid": "204.9.54.119",
"st": 2,
"t": "u",
"when": null,
"poll": 64,
"reach": 1,
"delay": 70.337,
"offset": -2.909,
"jitter": 2.6,
"state": null
},
{
"remote": "mirror1.sjc02.s",
"refid": "216.218.254.202",
"st": 2,
"t": "u",
"when": 2,
"poll": 64,
"reach": 1,
"delay": 29.325,
"offset": 1.044,
"jitter": 4.069,
"state": null,
}
]
$ ntpq -pn| jc --ntpq -p
[
{
"remote": "44.190.6.254",
"refid": "127.67.113.92",
"st": 2,
"t": "u",
"when": 66,
"poll": 64,
"reach": 377,
"delay": 22.69,
"offset": -0.392,
"jitter": 2.085,
"state": "+"
},
{
"remote": "108.59.2.24",
"refid": "130.133.1.10",
"st": 2,
"t": "u",
"when": 63,
"poll": 64,
"reach": 377,
"delay": 90.805,
"offset": 2.84,
"jitter": 1.908,
"state": "-"
},
{
"remote": "38.229.71.1",
"refid": "204.9.54.119",
"st": 2,
"t": "u",
"when": 64,
"poll": 64,
"reach": 377,
"delay": 68.699,
"offset": -0.61,
"jitter": 2.576,
"state": "+"
},
{
"remote": "72.5.72.15",
"refid": "216.218.254.202",
"st": 2,
"t": "u",
"when": 63,
"poll": 64,
"reach": 377,
"delay": 22.654,
"offset": 0.231,
"jitter": 1.964,
"state": "*"
}
]
$ ntpq -pn| jc --ntpq -p -r
[
{
"s": "+",
"remote": "44.190.6.254",
"refid": "127.67.113.92",
"st": "2",
"t": "u",
"when": "66",
"poll": "64",
"reach": "377",
"delay": "22.690",
"offset": "-0.392",
"jitter": "2.085"
},
{
"s": "-",
"remote": "108.59.2.24",
"refid": "130.133.1.10",
"st": "2",
"t": "u",
"when": "63",
"poll": "64",
"reach": "377",
"delay": "90.805",
"offset": "2.840",
"jitter": "1.908"
},
{
"s": "+",
"remote": "38.229.71.1",
"refid": "204.9.54.119",
"st": "2",
"t": "u",
"when": "64",
"poll": "64",
"reach": "377",
"delay": "68.699",
"offset": "-0.610",
"jitter": "2.576"
},
{
"s": "*",
"remote": "72.5.72.15",
"refid": "216.218.254.202",
"st": "2",
"t": "u",
"when": "63",
"poll": "64",
"reach": "377",
"delay": "22.654",
"offset": "0.231",
"jitter": "1.964"
}
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"state": string, # space/~ converted to null
"remote": string,
"refid": string,
"st": integer,
"t": string,
"when": integer, # - converted to null
"poll": integer,
"reach": integer,
"delay": float,
"offset": float,
"jitter": float
},
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

126
docs/parsers/passwd.md Normal file
View File

@@ -0,0 +1,126 @@
# jc.parsers.passwd
jc - JSON CLI output utility /etc/passwd file Parser
Usage:
specify --passwd as the first argument if the piped input is coming from /etc/passwd
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ cat /etc/passwd | jc --passwd -p
[
{
"username": "nobody",
"password": "*",
"uid": -2,
"gid": -2,
"comment": "Unprivileged User",
"home": "/var/empty",
"shell": "/usr/bin/false"
},
{
"username": "root",
"password": "*",
"uid": 0,
"gid": 0,
"comment": "System Administrator",
"home": "/var/root",
"shell": "/bin/sh"
},
{
"username": "daemon",
"password": "*",
"uid": 1,
"gid": 1,
"comment": "System Services",
"home": "/var/root",
"shell": "/usr/bin/false"
},
...
]
$ cat /etc/passwd | jc --passwd -p -r
[
{
"username": "nobody",
"password": "*",
"uid": "-2",
"gid": "-2",
"comment": "Unprivileged User",
"home": "/var/empty",
"shell": "/usr/bin/false"
},
{
"username": "root",
"password": "*",
"uid": "0",
"gid": "0",
"comment": "System Administrator",
"home": "/var/root",
"shell": "/bin/sh"
},
{
"username": "daemon",
"password": "*",
"uid": "1",
"gid": "1",
"comment": "System Services",
"home": "/var/root",
"shell": "/usr/bin/false"
},
...
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"username": string,
"password": string,
"uid": integer,
"gid": integer,
"comment": string,
"home": string,
"shell": string
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

133
docs/parsers/shadow.md Normal file
View File

@@ -0,0 +1,133 @@
# jc.parsers.shadow
jc - JSON CLI output utility /etc/shadow file Parser
Usage:
specify --shadow as the first argument if the piped input is coming from /etc/shadow
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ sudo cat /etc/shadow | jc --shadow -p
[
{
"username": "root",
"password": "*",
"last_changed": 18113,
"minimum": 0,
"maximum": 99999,
"warn": 7,
"inactive": null,
"expire": null
},
{
"username": "daemon",
"password": "*",
"last_changed": 18113,
"minimum": 0,
"maximum": 99999,
"warn": 7,
"inactive": null,
"expire": null
},
{
"username": "bin",
"password": "*",
"last_changed": 18113,
"minimum": 0,
"maximum": 99999,
"warn": 7,
"inactive": null,
"expire": null
},
...
]
$ sudo cat /etc/shadow | jc --shadow -p -r
[
{
"username": "root",
"password": "*",
"last_changed": "18113",
"minimum": "0",
"maximum": "99999",
"warn": "7",
"inactive": "",
"expire": ""
},
{
"username": "daemon",
"password": "*",
"last_changed": "18113",
"minimum": "0",
"maximum": "99999",
"warn": "7",
"inactive": "",
"expire": ""
},
{
"username": "bin",
"password": "*",
"last_changed": "18113",
"minimum": "0",
"maximum": "99999",
"warn": "7",
"inactive": "",
"expire": ""
},
...
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"username": string,
"password": string,
"last_changed": integer,
"minimum": integer,
"maximum": integer,
"warn": integer,
"inactive": integer,
"expire": integer
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

View File

@@ -0,0 +1,87 @@
# jc.parsers.timedatectl
jc - JSON CLI output utility timedatectl Parser
Usage:
specify --timedatectl as the first argument if the piped input is coming from timedatectl or timedatectl status
Compatibility:
'linux'
Examples:
$ timedatectl | jc --timedatectl -p
{
"local_time": "Tue 2020-03-10 17:53:21 PDT",
"universal_time": "Wed 2020-03-11 00:53:21 UTC",
"rtc_time": "Wed 2020-03-11 00:53:21",
"time_zone": "America/Los_Angeles (PDT, -0700)",
"ntp_enabled": true,
"ntp_synchronized": true,
"rtc_in_local_tz": false,
"dst_active": true
}
$ timedatectl | jc --timedatectl -p -r
{
"local_time": "Tue 2020-03-10 17:53:21 PDT",
"universal_time": "Wed 2020-03-11 00:53:21 UTC",
"rtc_time": "Wed 2020-03-11 00:53:21",
"time_zone": "America/Los_Angeles (PDT, -0700)",
"ntp_enabled": "yes",
"ntp_synchronized": "yes",
"rtc_in_local_tz": "no",
"dst_active": "yes"
}
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
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:
{
"local_time": string,
"universal_time": string,
"rtc_time": string,
"time_zone": string,
"ntp_enabled": boolean,
"ntp_synchronized": boolean,
"system_clock_synchronized": boolean,
"systemd-timesyncd.service_active": boolean,
"rtc_in_local_tz": boolean,
"dst_active": boolean
}
## parse
```python
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.

152
docs/parsers/who.md Normal file
View File

@@ -0,0 +1,152 @@
# jc.parsers.who
jc - JSON CLI output utility who Parser
Usage:
specify --who as the first argument if the piped input is coming from who
accepts any of the following who options (or no options): -aTH
Compatibility:
'linux', 'darwin', 'cygwin', 'aix', 'freebsd'
Examples:
$ who -a | jc --who -p
[
{
"event": "reboot",
"time": "Feb 7 23:31",
"pid": 1
},
{
"user": "joeuser",
"writeable_tty": "-",
"tty": "console",
"time": "Feb 7 23:32",
"idle": "old",
"pid": 105
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys000",
"time": "Feb 13 16:44",
"idle": ".",
"pid": 51217,
"comment": "term=0 exit=0"
},
{
"user": "joeuser",
"writeable_tty": "?",
"tty": "ttys003",
"time": "Feb 28 08:59",
"idle": "01:36",
"pid": 41402
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys004",
"time": "Mar 1 16:35",
"idle": ".",
"pid": 15679,
"from": "192.168.1.5"
}
]
$ who -a | jc --who -p -r
[
{
"event": "reboot",
"time": "Feb 7 23:31",
"pid": "1"
},
{
"user": "joeuser",
"writeable_tty": "-",
"tty": "console",
"time": "Feb 7 23:32",
"idle": "old",
"pid": "105"
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys000",
"time": "Feb 13 16:44",
"idle": ".",
"pid": "51217",
"comment": "term=0 exit=0"
},
{
"user": "joeuser",
"writeable_tty": "?",
"tty": "ttys003",
"time": "Feb 28 08:59",
"idle": "01:36",
"pid": "41402"
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys004",
"time": "Mar 1 16:35",
"idle": ".",
"pid": "15679",
"from": "192.168.1.5"
}
]
## info
```python
info(self, /, *args, **kwargs)
```
## process
```python
process(proc_data)
```
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"user": string,
"event": string,
"writeable_tty": string,
"tty": string,
"time": string,
"idle": string,
"pid": integer,
"from": string,
"comment": string
}
]
## parse
```python
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:
List of dictionaries. Raw or processed structured data.

265
jc/cli.py
View File

@@ -9,11 +9,16 @@ import importlib
import textwrap
import signal
import json
from pygments import highlight
from pygments.style import Style
from pygments.token import (Name, Number, String, Keyword)
from pygments.lexers import JsonLexer
from pygments.formatters import Terminal256Formatter
import jc.utils
class info():
version = '1.7.4'
version = '1.10.8'
description = 'jc cli output JSON conversion tool'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -22,15 +27,22 @@ class info():
__version__ = info.version
parsers = [
'airport',
'airport-s',
'arp',
'blkid',
'crontab',
'crontab-u',
'csv',
'df',
'dig',
'du',
'env',
'file',
'free',
'fstab',
'group',
'gshadow',
'history',
'hosts',
'id',
@@ -38,30 +50,93 @@ parsers = [
'ini',
'iptables',
'jobs',
'last',
'ls',
'lsblk',
'lsmod',
'lsof',
'mount',
'netstat',
'ntpq',
'passwd',
'pip-list',
'pip-show',
'ps',
'route',
'shadow',
'ss',
'stat',
'systemctl',
'systemctl-lj',
'systemctl-ls',
'systemctl-luf',
'timedatectl',
'uname',
'uptime',
'w',
'who',
'xml',
'yaml'
]
def set_env_colors():
"""
Grab custom colors from JC_COLORS environment variable. JC_COLORS env variable takes 4 comma
separated string values and should be in the format of:
JC_COLORS=<keyname_color>,<keyword_color>,<number_color>,<string_color>
Where colors are: black, red, green, yellow, blue, magenta, cyan, gray, brightblack, brightred,
brightgreen, brightyellow, brightblue, brightmagenta, brightcyan, white, default
Default colors:
JC_COLORS=blue,brightblack,magenta,green
or
JC_COLORS=default,default,default,default
"""
env_colors = os.getenv('JC_COLORS')
input_error = False
if env_colors:
color_list = env_colors.split(',')
else:
input_error = True
if env_colors and len(color_list) != 4:
print('jc: Warning: could not parse JC_COLORS environment variable\n', file=sys.stderr)
input_error = True
if env_colors:
for color in color_list:
if color not in ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'gray', 'brightblack', 'brightred',
'brightgreen', 'brightyellow', 'brightblue', 'brightmagenta', 'brightcyan', 'white', 'default']:
print('jc: Warning: could not parse JC_COLORS environment variable\n', file=sys.stderr)
input_error = True
# if there is an issue with the env variable, just set all colors to default and move on
if input_error:
color_list = ['default', 'default', 'default', 'default']
# Try the color set in the JC_COLORS env variable first. If it is set to default, then fall back to default colors
return {
Name.Tag: f'bold ansi{color_list[0]}' if not color_list[0] == 'default' else f'bold ansiblue', # key names
Keyword: f'ansi{color_list[1]}' if not color_list[1] == 'default' else f'ansibrightblack', # true, false, null
Number: f'ansi{color_list[2]}' if not color_list[2] == 'default' else f'ansimagenta', # numbers
String: f'ansi{color_list[3]}' if not color_list[3] == 'default' else f'ansigreen' # strings
}
def piped_output():
"""returns False if stdout is a TTY. True if output is being piped to another program"""
if sys.stdout.isatty():
return False
else:
return True
def ctrlc(signum, frame):
"""exit with error on SIGINT"""
sys.exit(1)
@@ -145,10 +220,6 @@ def helptext(message):
Usage: COMMAND | jc PARSER [OPTIONS]
or
COMMAND | jc [OPTIONS] PARSER
or magic syntax:
jc [OPTIONS] COMMAND
@@ -158,6 +229,7 @@ def helptext(message):
Options:
-a about jc
-d debug - show trace messages
-m monochrome output
-p pretty print output
-q quiet - suppress warnings
-r raw JSON output
@@ -172,111 +244,121 @@ def helptext(message):
print(textwrap.dedent(helptext_string), file=sys.stderr)
def json_out(data, pretty=False):
if pretty:
print(json.dumps(data, indent=2))
def json_out(data, pretty=False, mono=False, piped_out=False):
# set colors
class JcStyle(Style):
styles = set_env_colors()
if not mono and not piped_out:
if pretty:
print(highlight(json.dumps(data, indent=2), JsonLexer(), Terminal256Formatter(style=JcStyle))[0:-1])
else:
print(highlight(json.dumps(data), JsonLexer(), Terminal256Formatter(style=JcStyle))[0:-1])
else:
print(json.dumps(data))
if pretty:
print(json.dumps(data, indent=2))
else:
print(json.dumps(data))
def generate_magic_command(args):
"""
Returns a tuple with a boolean and a command, where the boolean signifies that
the command is valid, and the command is either a command string or None.
"""
# Parse with magic syntax: jc -p ls -al
if len(args) <= 1 or args[1].startswith('--'):
return False, None
# correctly parse escape characters and spaces with shlex
args_given = ' '.join(map(shlex.quote, args[1:])).split()
options = []
# find the options
for arg in list(args_given):
# parser found - use standard syntax
if arg.startswith('--'):
return False, None
# option found - populate option list
elif arg.startswith('-'):
options.extend(args_given.pop(0)[1:])
# command found if iterator didn't already stop - stop iterating
else:
break
# all options popped and no command found - for case like 'jc -a'
if len(args_given) == 0:
return False, None
magic_dict = {}
parser_info = about_jc()['parsers']
# Create a dictionary of magic_commands to their respective parsers.
for entry in parser_info:
# Update the dict with all of the magic commands for this parser, if they exist.
magic_dict.update({mc: entry['argument'] for mc in entry.get('magic_commands', [])})
# find the command and parser
one_word_command = args_given[0]
two_word_command = ' '.join(args_given[0:2])
# Try to get a parser for two_word_command, otherwise get one for one_word_command
found_parser = magic_dict.get(two_word_command, magic_dict.get(one_word_command))
# construct a new command line using the standard syntax: COMMAND | jc --PARSER -OPTIONS
run_command = ' '.join(args_given)
if found_parser:
cmd_options = ('-' + ''.join(options)) if options else ''
return True, ' '.join([run_command, '|', 'jc', found_parser, cmd_options])
else:
return False, run_command
def magic():
"""Parse with magic syntax: jc -p ls -al"""
if len(sys.argv) > 1 and not sys.argv[1].startswith('--'):
parser_info = about_jc()['parsers']
# correctly parse escape characters and spaces with shlex
args_given = " ".join(map(shlex.quote, sys.argv[1:])).split()
options = []
found_parser = None
# find the options
if args_given[0].startswith('-'):
p = 0
for i, arg in list(enumerate(args_given)):
# parser found - use standard syntax
if arg.startswith('--'):
return
# option found - populate option list
elif arg.startswith('-'):
options.append(args_given.pop(i - p)[1:])
p = p + 1
# command found if iterator didn't already stop - stop iterating
else:
break
# find the command and parser
for parser in parser_info:
if 'magic_commands' in parser:
# first pass for two word commands: e.g. 'pip list'
for magic_command in parser['magic_commands']:
try:
if ' '.join(args_given[0:2]) == magic_command:
found_parser = parser['argument']
break
# No command found - go to next loop (for cases like 'jc -a')
except Exception:
break
# second pass for one word commands: e.g. 'ls'
if not found_parser:
for magic_command in parser['magic_commands']:
try:
if args_given[0] == magic_command:
found_parser = parser['argument']
break
# No command found - use standard syntax (for cases like 'jc -a')
except Exception:
return
# construct a new command line using the standard syntax: COMMAND | jc --PARSER -OPTIONS
run_command = ' '.join(args_given)
if found_parser:
if options:
cmd_options = '-' + ''.join(options)
else:
cmd_options = ''
whole_command = ' '.join([run_command, '|', 'jc', found_parser, cmd_options])
os.system(whole_command)
exit()
else:
helptext(f'parser not found for "{run_command}"')
sys.exit(1)
valid_command, run_command = generate_magic_command(sys.argv)
if valid_command:
os.system(run_command)
sys.exit(0)
elif run_command is None:
return
else:
helptext(f'parser not found for "{run_command}"')
sys.exit(1)
def main():
# break on ctrl-c keyboard interrupt
signal.signal(signal.SIGINT, ctrlc)
# break on pipe error. need try/except for windows compatibility
try:
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError:
pass
# try magic syntax first: e.g. jc -p ls -al
magic()
options = []
debug = False
pretty = False
quiet = False
raw = False
# options
for opt in sys.argv:
if opt.startswith('-') and not opt.startswith('--'):
for flag in opt[1:]:
options.append(flag)
options.extend(opt[1:])
if 'd' in options:
debug = True
if 'p' in options:
pretty = True
if 'q' in options:
quiet = True
if 'r' in options:
raw = True
debug = 'd' in options
mono = 'm' in options
pretty = 'p' in options
quiet = 'q' in options
raw = 'r' in options
if 'a' in options:
json_out(about_jc(), pretty=pretty)
exit()
json_out(about_jc(), pretty=pretty, mono=mono, piped_out=piped_output())
sys.exit(0)
if sys.stdin.isatty():
helptext('missing piped data')
@@ -308,14 +390,15 @@ def main():
found = True
break
except Exception:
jc.utils.error_message(f'{parser_name} parser could not parse the input data. Did you use the correct parser?\n For details use the -d option.')
jc.utils.error_message(
f'{parser_name} parser could not parse the input data. Did you use the correct parser?\n For details use the -d option.')
sys.exit(1)
if not found:
helptext('missing or incorrect arguments')
sys.exit(1)
json_out(result, pretty=pretty)
json_out(result, pretty=pretty, mono=mono, piped_out=piped_output())
if __name__ == '__main__':

141
jc/parsers/airport.py Normal file
View File

@@ -0,0 +1,141 @@
"""jc - JSON CLI output utility airport -I Parser
Usage:
specify --airport as the first argument if the piped input is coming from airport -I (OSX)
This program can be found at:
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport
Compatibility:
'darwin'
Examples:
$ airport -I | jc --airport -p
{
"agrctlrssi": -66,
"agrextrssi": 0,
"agrctlnoise": -90,
"agrextnoise": 0,
"state": "running",
"op_mode": "station",
"lasttxrate": 195,
"maxrate": 867,
"lastassocstatus": 0,
"802_11_auth": "open",
"link_auth": "wpa2-psk",
"bssid": "3c:37:86:15:ad:f9",
"ssid": "SnazzleDazzle",
"mcs": 0,
"channel": "48,80"
}
$ airport -I | jc --airport -p -r
{
"agrctlrssi": "-66",
"agrextrssi": "0",
"agrctlnoise": "-90",
"agrextnoise": "0",
"state": "running",
"op_mode": "station",
"lasttxrate": "195",
"maxrate": "867",
"lastassocstatus": "0",
"802_11_auth": "open",
"link_auth": "wpa2-psk",
"bssid": "3c:37:86:15:ad:f9",
"ssid": "SnazzleDazzle",
"mcs": "0",
"channel": "48,80"
}
"""
import jc.utils
class info():
version = '1.0'
description = 'airport -I 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 = ['darwin']
magic_commands = ['airport -I']
__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:
{
"agrctlrssi": integer,
"agrextrssi": integer,
"agrctlnoise": integer,
"agrextnoise": integer,
"state": string,
"op_mode": string,
"lasttxrate": integer,
"maxrate": integer,
"lastassocstatus": integer,
"802_11_auth": string,
"link_auth": string,
"bssid": string,
"ssid": string,
"mcs": integer,
"channel": string
}
"""
# integer changes
int_list = ['agrctlrssi', 'agrextrssi', 'agrctlnoise', 'agrextnoise',
'lasttxrate', 'maxrate', 'lastassocstatus', 'mcs']
for key in proc_data:
if key in int_list:
try:
proc_data[key] = int(proc_data[key])
except (ValueError):
proc_data[key] = None
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 = {}
for line in filter(None, data.splitlines()):
linedata = line.split(':', maxsplit=1)
raw_output[linedata[0].strip().lower().replace(' ', '_').replace('.', '_')] = linedata[1].strip()
if raw:
return raw_output
else:
return process(raw_output)

186
jc/parsers/airport_s.py Normal file
View File

@@ -0,0 +1,186 @@
"""jc - JSON CLI output utility airport -s Parser
Usage:
specify --airport as the first argument if the piped input is coming from airport -s (OSX)
This program can be found at:
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport
Compatibility:
'darwin'
Examples:
$ airport -s | jc --airport-s -p
[
{
"ssid": "DIRECT-4A-HP OfficeJet 3830",
"bssid": "00:67:eb:2a:a7:3b",
"rssi": -90,
"channel": "6",
"ht": true,
"cc": "--",
"security": [
"WPA2(PSK/AES/AES)"
]
},
{
"ssid": "Latitude38",
"bssid": "c0:ff:d5:d2:7a:f3",
"rssi": -85,
"channel": "11",
"ht": true,
"cc": "US",
"security": [
"WPA2(PSK/AES/AES)"
]
},
{
"ssid": "xfinitywifi",
"bssid": "6e:e3:0e:b8:45:99",
"rssi": -83,
"channel": "11",
"ht": true,
"cc": "US",
"security": [
"NONE"
]
},
...
]
$ airport -s | jc --airport -p -r
[
{
"ssid": "DIRECT-F3-HP ENVY 5660 series",
"bssid": "b0:5a:da:6f:0a:d4",
"rssi": "-93",
"channel": "1",
"ht": "Y",
"cc": "--",
"security": "WPA2(PSK/AES/AES)"
},
{
"ssid": "YouAreInfected-5",
"bssid": "5c:e3:0e:c2:85:da",
"rssi": "-85",
"channel": "36",
"ht": "Y",
"cc": "US",
"security": "WPA(PSK/AES,TKIP/TKIP) WPA2(PSK/AES,TKIP/TKIP)"
},
{
"ssid": "YuanFamily",
"bssid": "5c:e3:0e:b8:5f:9a",
"rssi": "-84",
"channel": "11",
"ht": "Y",
"cc": "US",
"security": "WPA(PSK/AES,TKIP/TKIP) WPA2(PSK/AES,TKIP/TKIP)"
},
...
]
"""
import jc.utils
import jc.parsers.universal
class info():
version = '1.0'
description = 'airport -s 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 = ['darwin']
magic_commands = ['airport -s']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"ssid": string,
"bssid": string,
"rssi": integer,
"channel": string,
"ht": boolean,
"cc": string,
"security": [
string,
]
}
]
"""
for entry in proc_data:
# integers
int_list = ['rssi']
for key in int_list:
if key in entry:
try:
entry[key] = int(entry[key])
except (ValueError):
entry[key] = None
# booleans
bool_list = ['ht']
for key in entry:
if key in bool_list:
try:
entry[key] = True if entry[key] == 'Y' else False
except (ValueError):
entry[key] = None
if 'security' in entry:
entry['security'] = entry['security'].split()
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
cleandata = data.splitlines()
# fix headers
cleandata[0] = cleandata[0].lower()
cleandata[0] = cleandata[0].replace('-', '_')
cleandata[0] = cleandata[0].replace('security (auth/unicast/group)', 'security')
# parse the data
raw_output = jc.parsers.universal.sparse_table_parse(cleandata)
if raw:
return raw_output
else:
return process(raw_output)

View File

@@ -91,7 +91,7 @@ import jc.parsers.universal
class info():
version = '1.1'
version = '1.3'
description = 'arp command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -156,20 +156,21 @@ def parse(data, raw=False, quiet=False):
cleandata = data.splitlines()
# remove final Entries row if -v was used
if cleandata[-1].find('Entries:') == 0:
if cleandata[-1].startswith('Entries:'):
cleandata.pop(-1)
# detect if osx style was used
if cleandata[0].find(' ifscope ') != -1:
if cleandata[0][-1] == ']':
raw_output = []
for line in cleandata:
line = line.split()
output_line = {}
output_line['name'] = line[0]
output_line['address'] = line[1].lstrip('(').rstrip(')')
output_line['hwtype'] = line[-1].lstrip('[').rstrip(']')
output_line['hwaddress'] = line[3]
output_line['iface'] = line[5]
splitline = line.split()
output_line = {
'name': splitline[0],
'address': splitline[1].lstrip('(').rstrip(')'),
'hwtype': splitline[-1].lstrip('[').rstrip(']'),
'hwaddress': splitline[3],
'iface': splitline[5]
}
raw_output.append(output_line)
if raw:
@@ -178,7 +179,7 @@ def parse(data, raw=False, quiet=False):
return process(raw_output)
# detect if linux style was used
elif cleandata[0].find('Address') == 0:
elif cleandata[0].startswith('Address'):
# fix header row to change Flags Mask to flags_mask
cleandata[0] = cleandata[0].replace('Flags Mask', 'flags_mask')
@@ -196,12 +197,13 @@ def parse(data, raw=False, quiet=False):
raw_output = []
for line in cleandata:
line = line.split()
output_line = {}
output_line['name'] = line[0]
output_line['address'] = line[1].lstrip('(').rstrip(')')
output_line['hwtype'] = line[4].lstrip('[').rstrip(']')
output_line['hwaddress'] = line[3]
output_line['iface'] = line[6]
output_line = {
'name': line[0],
'address': line[1].lstrip('(').rstrip(')'),
'hwtype': line[4].lstrip('[').rstrip(']'),
'hwaddress': line[3],
'iface': line[6],
}
raw_output.append(output_line)
if raw:

218
jc/parsers/blkid.py Normal file
View File

@@ -0,0 +1,218 @@
"""jc - JSON CLI output utility blkid Parser
Usage:
specify --blkid as the first argument if the piped input is coming from blkid
Compatibility:
'linux'
Examples:
$ blkid | jc --blkid -p
[
{
"device": "/dev/sda1",
"uuid": "05d927ab-5875-49e4-ada1-7f46cb32c932",
"type": "xfs"
},
{
"device": "/dev/sda2",
"uuid": "3klkIj-w1kk-DkJi-0XBJ-y3i7-i2Ac-vHqWBM",
"type": "LVM2_member"
},
{
"device": "/dev/mapper/centos-root",
"uuid": "07d718ff-950c-4e5b-98f0-42a1147c77d9",
"type": "xfs"
},
{
"device": "/dev/mapper/centos-swap",
"uuid": "615eb89a-bcbf-46fd-80e3-c483ff5c931f",
"type": "swap"
}
]
$ sudo blkid -o udev -ip /dev/sda2 | jc --blkid -p
[
{
"id_fs_uuid": "3klkIj-w1kk-DkJi-0XBJ-y3i7-i2Ac-vHqWBM",
"id_fs_uuid_enc": "3klkIj-w1kk-DkJi-0XBJ-y3i7-i2Ac-vHqWBM",
"id_fs_version": "LVM2\\x20001",
"id_fs_type": "LVM2_member",
"id_fs_usage": "raid",
"id_iolimit_minimum_io_size": 512,
"id_iolimit_physical_sector_size": 512,
"id_iolimit_logical_sector_size": 512,
"id_part_entry_scheme": "dos",
"id_part_entry_type": "0x8e",
"id_part_entry_number": 2,
"id_part_entry_offset": 2099200,
"id_part_entry_size": 39843840,
"id_part_entry_disk": "8:0"
}
]
$ sudo blkid -ip /dev/sda1 | jc --blkid -p -r
[
{
"devname": "/dev/sda1",
"uuid": "05d927bb-5875-49e3-ada1-7f46cb31c932",
"type": "xfs",
"usage": "filesystem",
"minimum_io_size": "512",
"physical_sector_size": "512",
"logical_sector_size": "512",
"part_entry_scheme": "dos",
"part_entry_type": "0x83",
"part_entry_flags": "0x80",
"part_entry_number": "1",
"part_entry_offset": "2048",
"part_entry_size": "2097152",
"part_entry_disk": "8:0"
}
]
"""
import shlex
import jc.utils
class info():
version = '1.0'
description = 'blkid 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']
magic_commands = ['blkid']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"device": string,
"uuid": string,
"type": string,
"usage": string,
"part_entry_scheme": string,
"part_entry_type": string,
"part_entry_flags": string,
"part_entry_number": integer,
"part_entry_offset": integer,
"part_entry_size": integer,
"part_entry_disk": string,
"id_fs_uuid": string,
"id_fs_uuid_enc": string,
"id_fs_version": string,
"id_fs_type": string,
"id_fs_usage": string,
"id_part_entry_scheme": string,
"id_part_entry_type": string,
"id_part_entry_flags": string,
"id_part_entry_number": integer,
"id_part_entry_offset": integer,
"id_part_entry_size": integer,
"id_iolimit_minimum_io_size": integer,
"id_iolimit_physical_sector_size": integer,
"id_iolimit_logical_sector_size": integer,
"id_part_entry_disk": string,
"minimum_io_size": integer,
"physical_sector_size": integer,
"logical_sector_size": integer
}
]
"""
for entry in proc_data:
if 'devname' in entry:
entry['device'] = entry.pop('devname')
int_list = ['part_entry_number', 'part_entry_offset', 'part_entry_size', 'id_part_entry_number',
'id_part_entry_offset', 'id_part_entry_size', 'minimum_io_size', 'physical_sector_size',
'logical_sector_size', 'id_iolimit_minimum_io_size', 'id_iolimit_physical_sector_size',
'id_iolimit_logical_sector_size']
for key in int_list:
if key in entry:
try:
entry[key] = int(entry[key])
except (ValueError):
entry[key] = None
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
if data:
# if the first field is a device, use normal parsing:
if data.split(maxsplit=1)[0][-1] == ':':
linedata = data.splitlines()
for line in linedata:
output_line = {}
entries = shlex.split(line)
output_line['device'] = entries.pop(0)[:-1]
for entry in entries:
key = entry.split('=', maxsplit=1)[0].lower()
value = entry.split('=', maxsplit=1)[1]
output_line[key] = value
raw_output.append(output_line)
# else use key/value per line parsing
else:
linedata = data.splitlines()
output_line = {}
for line in linedata:
if line == '':
if output_line:
raw_output.append(output_line)
output_line = {}
continue
continue
key = line.split('=', maxsplit=1)[0].lower()
value = line.split('=', maxsplit=1)[1]
output_line[key] = value
if output_line:
raw_output.append(output_line)
if raw:
return raw_output
else:
return process(raw_output)

View File

@@ -132,7 +132,7 @@ import jc.parsers.universal
class info():
version = '1.1'
version = '1.2'
description = 'crontab command and file parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -227,13 +227,13 @@ def parse(data, raw=False, quiet=False):
# Clear any commented lines
for i, line in reversed(list(enumerate(cleandata))):
if line.strip().find('#') == 0:
if line.strip().startswith('#'):
cleandata.pop(i)
# Pop any variable assignment lines
cron_var = []
for i, line in reversed(list(enumerate(cleandata))):
if line.find('=') != -1:
if '=' in line:
var_line = cleandata.pop(i)
var_name = var_line.split('=', maxsplit=1)[0].strip()
var_value = var_line.split('=', maxsplit=1)[1].strip()

View File

@@ -133,7 +133,7 @@ import jc.parsers.universal
class info():
version = '1.0'
version = '1.1'
description = 'crontab file parser with user support'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -228,13 +228,13 @@ def parse(data, raw=False, quiet=False):
# Clear any commented lines
for i, line in reversed(list(enumerate(cleandata))):
if line.strip().find('#') == 0:
if line.strip().startswith('#'):
cleandata.pop(i)
# Pop any variable assignment lines
cron_var = []
for i, line in reversed(list(enumerate(cleandata))):
if line.find('=') != -1:
if '=' in line:
var_line = cleandata.pop(i)
var_name = var_line.split('=', maxsplit=1)[0].strip()
var_value = var_line.split('=', maxsplit=1)[1].strip()

141
jc/parsers/csv.py Normal file
View File

@@ -0,0 +1,141 @@
"""jc - JSON CLI output utility csv Parser
Usage:
specify --csv as the first argument if the piped input is coming from a csv file.
the csv parser will attempt to automatically detect the delimiter character.
if the delimiter cannot be detected it will default to comma.
the first row of the file must be a header row.
Compatibility:
'linux', 'darwin', 'cygwin', 'win32', 'aix', 'freebsd'
Examples:
$ cat homes.csv
"Sell", "List", "Living", "Rooms", "Beds", "Baths", "Age", "Acres", "Taxes"
142, 160, 28, 10, 5, 3, 60, 0.28, 3167
175, 180, 18, 8, 4, 1, 12, 0.43, 4033
129, 132, 13, 6, 3, 1, 41, 0.33, 1471
...
$ cat homes.csv | jc --csv -p
[
{
"Sell": "142",
"List": "160",
"Living": "28",
"Rooms": "10",
"Beds": "5",
"Baths": "3",
"Age": "60",
"Acres": "0.28",
"Taxes": "3167"
},
{
"Sell": "175",
"List": "180",
"Living": "18",
"Rooms": "8",
"Beds": "4",
"Baths": "1",
"Age": "12",
"Acres": "0.43",
"Taxes": "4033"
},
{
"Sell": "129",
"List": "132",
"Living": "13",
"Rooms": "6",
"Beds": "3",
"Baths": "1",
"Age": "41",
"Acres": "0.33",
"Taxes": "1471"
},
...
]
"""
import jc.utils
import csv
class info():
version = '1.0'
description = 'CSV file parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
details = 'Using the python standard csv library'
# compatible options: linux, darwin, cygwin, win32, aix, freebsd
compatible = ['linux', 'darwin', 'cygwin', 'win32', 'aix', 'freebsd']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Each dictionary represents a row in the csv file:
[
{
csv file converted to a Dictionary
https://docs.python.org/3/library/csv.html
}
]
"""
# No further processing
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
cleandata = data.splitlines()
# Clear any blank lines
cleandata = list(filter(None, cleandata))
if cleandata:
dialect = None
try:
dialect = csv.Sniffer().sniff(data[:1024])
except Exception:
pass
reader = csv.DictReader(cleandata, dialect=dialect)
for row in reader:
raw_output.append(row)
if raw:
return raw_output
else:
return process(raw_output)

View File

@@ -73,7 +73,7 @@ import jc.parsers.universal
class info():
version = '1.1'
version = '1.2'
description = 'df command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -135,7 +135,7 @@ def process(proc_data):
# change any entry for key with '_blocks' in the name to int
for k in entry:
if str(k).find('_blocks') != -1:
if '_blocks' in str(k):
try:
blocks_int = int(entry[k])
entry[k] = blocks_int

View File

@@ -324,7 +324,7 @@ import jc.utils
class info():
version = '1.0'
version = '1.2'
description = 'dig command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -361,6 +361,15 @@ def process(proc_data):
"answer_num": integer,
"authority_num": integer,
"additional_num": integer,
"axfr": [
{
"name": string,
"class": string,
"type": string,
"ttl": integer,
"data": string
}
],
"question": {
"name": string,
"class": string,
@@ -388,6 +397,7 @@ def process(proc_data):
"server": string,
"when": string,
"rcvd": integer
"size": string
}
]
"""
@@ -402,6 +412,14 @@ def process(proc_data):
except (ValueError):
entry[key] = None
if 'axfr' in entry:
for ax in entry['axfr']:
try:
ttl_int = int(ax['ttl'])
ax['ttl'] = ttl_int
except (ValueError):
ax['ttl'] = None
if 'answer' in entry:
for ans in entry['answer']:
try:
@@ -508,6 +526,25 @@ def parse_answer(answer):
'data': answer_data}
def parse_axfr(axfr):
# ; <<>> DiG 9.11.14-3-Debian <<>> @81.4.108.41 axfr zonetransfer.me +nocookie
# ; (1 server found)
# ;; global options: +cmd
# zonetransfer.me. 7200 IN A 5.196.105.14
axfr = axfr.split(maxsplit=4)
axfr_name = axfr[0]
axfr_ttl = axfr[1]
axfr_class = axfr[2]
axfr_type = axfr[3]
axfr_data = axfr[4]
return {'name': axfr_name,
'ttl': axfr_ttl,
'class': axfr_class,
'type': axfr_type,
'data': axfr_data}
def parse(data, raw=False, quiet=False):
"""
Main text parsing function
@@ -534,23 +571,38 @@ def parse(data, raw=False, quiet=False):
question = False
authority = False
answer = False
axfr = False
output_entry = {}
for line in cleandata:
if line.find(';; ->>HEADER<<-') == 0:
if line.startswith('; <<>> ') and ' axfr ' in line.lower():
question = False
authority = False
answer = False
axfr = True
axfr_list = []
continue
if ';' not in line and axfr:
axfr_list.append(parse_axfr(line))
output_entry.update({'axfr': axfr_list})
continue
if line.startswith(';; ->>HEADER<<-'):
output_entry = {}
output_entry.update(parse_header(line))
continue
if line.find(';; flags:') == 0:
if line.startswith(';; flags:'):
output_entry.update(parse_flags_line(line))
continue
if line.find(';; QUESTION SECTION:') == 0:
if line.startswith(';; QUESTION SECTION:'):
question = True
authority = False
answer = False
axfr = False
continue
if question:
@@ -558,52 +610,60 @@ def parse(data, raw=False, quiet=False):
question = False
authority = False
answer = False
axfr = False
continue
if line.find(';; AUTHORITY SECTION:') == 0:
if line.startswith(';; AUTHORITY SECTION:'):
question = False
authority = True
answer = False
axfr = False
authority_list = []
continue
if line.find(';') == -1 and authority:
if ';' not in line and authority:
authority_list.append(parse_authority(line))
output_entry.update({'authority': authority_list})
continue
if line.find(';; ANSWER SECTION:') == 0:
if line.startswith(';; ANSWER SECTION:'):
question = False
authority = False
answer = True
axfr = False
answer_list = []
continue
if line.find(';') == -1 and answer:
if ';' not in line and answer:
answer_list.append(parse_answer(line))
output_entry.update({'answer': answer_list})
continue
# footer consists of 4 lines
# footer line 1
if line.find(';; Query time:') == 0:
if line.startswith(';; Query time:'):
output_entry.update({'query_time': line.split(':')[1].lstrip()})
continue
# footer line 2
if line.find(';; SERVER:') == 0:
if line.startswith(';; SERVER:'):
output_entry.update({'server': line.split(':')[1].lstrip()})
continue
# footer line 3
if line.find(';; WHEN:') == 0:
if line.startswith(';; WHEN:'):
output_entry.update({'when': line.split(':', maxsplit=1)[1].lstrip()})
continue
# footer line 4 (last line)
if line.find(';; MSG SIZE rcvd:') == 0:
if line.startswith(';; MSG SIZE rcvd:'):
output_entry.update({'rcvd': line.split(':')[1].lstrip()})
if output_entry:
raw_output.append(output_entry)
elif line.startswith(';; XFR size:'):
output_entry.update({'size': line.split(':')[1].lstrip()})
if output_entry:
raw_output.append(output_entry)

128
jc/parsers/file.py Normal file
View File

@@ -0,0 +1,128 @@
"""jc - JSON CLI output utility file command Parser
Usage:
specify --file as the first argument if the piped input is coming from file.
Compatibility:
'linux', 'aix', 'freebsd', 'darwin'
Examples:
$ file * | jc --file -p
[
{
"filename": "Applications",
"type": "directory"
},
{
"filename": "another file with spaces",
"type": "empty"
},
{
"filename": "argstest.py",
"type": "Python script text executable, ASCII text"
},
{
"filename": "blkid-p.out",
"type": "ASCII text"
},
{
"filename": "blkid-pi.out",
"type": "ASCII text, with very long lines"
},
{
"filename": "cd_catalog.xml",
"type": "XML 1.0 document text, ASCII text, with CRLF line terminators"
},
{
"filename": "centosserial.sh",
"type": "Bourne-Again shell script text executable, UTF-8 Unicode text"
},
...
]
"""
import jc.utils
import jc.parsers.universal
class info():
version = '1.1'
description = 'file command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
# compatible options: linux, darwin, cygwin, win32, aix, freebsd
compatible = ['linux', 'aix', 'freebsd', 'darwin']
magic_commands = ['file']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"filename": string,
"type ": string
}
]
"""
# No further processing
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
warned = False
for line in filter(None, data.splitlines()):
linedata = line.rsplit(': ', maxsplit=1)
try:
filename = linedata[0].strip()
filetype = linedata[1].strip()
raw_output.append(
{
'filename': filename,
'type': filetype
}
)
except IndexError:
if not warned:
jc.utils.warning_message('Filenames with newline characters detected. Some filenames may be truncated.')
warned = True
if raw:
return raw_output
else:
return process(raw_output)

View File

@@ -77,12 +77,8 @@ def parse(data, raw=False, quiet=False):
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
cleandata = data.splitlines()
# Clear any blank lines
cleandata = list(filter(None, cleandata))
if cleandata:
for line in filter(None, data.splitlines()):
# parse the content
pass

View File

@@ -70,7 +70,7 @@ import jc.utils
class info():
version = '1.0'
version = '1.1'
description = 'fstab file parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -145,7 +145,7 @@ def parse(data, raw=False, quiet=False):
for line in cleandata:
output_line = {}
# ignore commented lines
if line.strip().find('#') == 0:
if line.strip().startswith('#'):
continue
line_list = line.split(maxsplit=6)

190
jc/parsers/group.py Normal file
View File

@@ -0,0 +1,190 @@
"""jc - JSON CLI output utility /etc/group file Parser
Usage:
specify --group as the first argument if the piped input is coming from /etc/group
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ cat /etc/group | jc --group -p
[
{
"group_name": "nobody",
"password": "*",
"gid": -2,
"members": []
},
{
"group_name": "nogroup",
"password": "*",
"gid": -1,
"members": []
},
{
"group_name": "wheel",
"password": "*",
"gid": 0,
"members": [
"root"
]
},
{
"group_name": "certusers",
"password": "*",
"gid": 29,
"members": [
"root",
"_jabber",
"_postfix",
"_cyrus",
"_calendar",
"_dovecot"
]
},
...
]
$ cat /etc/group | jc --group -p -r
[
{
"group_name": "nobody",
"password": "*",
"gid": "-2",
"members": [
""
]
},
{
"group_name": "nogroup",
"password": "*",
"gid": "-1",
"members": [
""
]
},
{
"group_name": "wheel",
"password": "*",
"gid": "0",
"members": [
"root"
]
},
{
"group_name": "certusers",
"password": "*",
"gid": "29",
"members": [
"root",
"_jabber",
"_postfix",
"_cyrus",
"_calendar",
"_dovecot"
]
},
...
]
"""
import jc.utils
class info():
version = '1.0'
description = '/etc/group file 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']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"group_name": string,
"password": string,
"gid": integer,
"members": [
string
]
}
]
"""
for entry in proc_data:
int_list = ['gid']
for key in int_list:
if key in entry:
try:
key_int = int(entry[key])
entry[key] = key_int
except (ValueError):
entry[key] = None
if entry['members'] == ['']:
entry['members'] = []
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
cleandata = data.splitlines()
# Clear any blank lines
cleandata = list(filter(None, cleandata))
if cleandata:
for entry in cleandata:
if entry.startswith('#'):
continue
output_line = {}
fields = entry.split(':')
output_line['group_name'] = fields[0]
output_line['password'] = fields[1]
output_line['gid'] = fields[2]
output_line['members'] = fields[3].split(',')
raw_output.append(output_line)
if raw:
return raw_output
else:
return process(raw_output)

152
jc/parsers/gshadow.py Normal file
View File

@@ -0,0 +1,152 @@
"""jc - JSON CLI output utility /etc/gshadow file Parser
Usage:
specify --gshadow as the first argument if the piped input is coming from /etc/gshadow
Compatibility:
'linux', 'aix', 'freebsd'
Examples:
$ cat /etc/gshadow | jc --gshadow -p
[
{
"group_name": "root",
"password": "*",
"administrators": [],
"members": []
},
{
"group_name": "adm",
"password": "*",
"administrators": [],
"members": [
"syslog",
"joeuser"
]
},
...
]
$ cat /etc/gshadow | jc --gshadow -p -r
[
{
"group_name": "root",
"password": "*",
"administrators": [
""
],
"members": [
""
]
},
{
"group_name": "adm",
"password": "*",
"administrators": [
""
],
"members": [
"syslog",
"joeuser"
]
},
...
]
"""
import jc.utils
class info():
version = '1.0'
description = '/etc/gshadow file 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', 'aix', 'freebsd']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"group_name": string,
"password": string,
"administrators": [
string
],
"members": [
string
]
}
]
"""
for entry in proc_data:
if entry['administrators'] == ['']:
entry['administrators'] = []
if entry['members'] == ['']:
entry['members'] = []
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
cleandata = data.splitlines()
# Clear any blank lines
cleandata = list(filter(None, cleandata))
if cleandata:
for entry in cleandata:
if entry.startswith('#'):
continue
output_line = {}
fields = entry.split(':')
output_line['group_name'] = fields[0]
output_line['password'] = fields[1]
output_line['administrators'] = fields[2].split(',')
output_line['members'] = fields[3].split(',')
raw_output.append(output_line)
if raw:
return raw_output
else:
return process(raw_output)

View File

@@ -40,14 +40,15 @@ Examples:
...
}
"""
import jc
import jc.utils
class info():
version = '1.1'
version = '1.2'
description = 'history command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
details = 'Optimizations by https://github.com/philippeitis'
# compatible options: linux, darwin, cygwin, win32, aix, freebsd
compatible = ['linux', 'darwin', 'cygwin', 'aix', 'freebsd']
@@ -79,21 +80,11 @@ def process(proc_data):
# rebuild output for added semantic information
processed = []
for k, v in proc_data.items():
proc_line = {}
proc_line['line'] = k
proc_line['command'] = v
proc_line = {
'line': int(k) if k.isdigit() else None,
'command': v,
}
processed.append(proc_line)
for entry in processed:
int_list = ['line']
for key in int_list:
if key in entry:
try:
key_int = int(entry[key])
entry[key] = key_int
except (ValueError):
entry[key] = None
return processed
@@ -120,17 +111,14 @@ def parse(data, raw=False, quiet=False):
# split lines and clear out any non-ascii chars
linedata = data.encode('ascii', errors='ignore').decode().splitlines()
# Clear any blank lines
cleandata = list(filter(None, linedata))
if cleandata:
for entry in cleandata:
try:
parsed_line = entry.split(maxsplit=1)
raw_output[parsed_line[0]] = parsed_line[1]
except IndexError:
# need to catch indexerror in case there is weird input from prior commands
pass
# Skip any blank lines
for entry in filter(None, linedata):
try:
parsed_line = entry.split(maxsplit=1)
raw_output[parsed_line[0]] = parsed_line[1]
except IndexError:
# need to catch indexerror in case there is weird input from prior commands
pass
if raw:
return raw_output

View File

@@ -61,7 +61,7 @@ import jc.utils
class info():
version = '1.0'
version = '1.1'
description = '/etc/hosts file parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -126,7 +126,7 @@ def parse(data, raw=False, quiet=False):
for line in cleandata:
output_line = {}
# ignore commented lines
if line.strip().find('#') == 0:
if line.strip().startswith('#'):
continue
line_list = line.split(maxsplit=1)
@@ -136,7 +136,7 @@ def parse(data, raw=False, quiet=False):
comment_found = False
for i, item in enumerate(hosts_list):
if item.find('#') != -1:
if '#' in item:
comment_found = True
comment_item = i
break

View File

@@ -141,16 +141,17 @@ Examples:
}
]
"""
import re
from collections import namedtuple
import jc.utils
from ifconfigparser import IfconfigParser
class info():
version = '1.5'
version = '1.7'
description = 'ifconfig command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
details = 'Using ifconfig-parser package from https://github.com/KnightWhoSayNi/ifconfig-parser'
details = 'Using ifconfig-parser from https://github.com/KnightWhoSayNi/ifconfig-parser'
# compatible options: linux, darwin, cygwin, win32, aix, freebsd
compatible = ['linux', 'aix', 'freebsd', 'darwin']
@@ -160,6 +161,200 @@ class info():
__version__ = info.version
class IfconfigParser(object):
# Author: threeheadedknight@protonmail.com
# Date created: 30.06.2018 17:03
# Python Version: 3.7
attributes = ['name', 'type', 'mac_addr', 'ipv4_addr', 'ipv4_bcast', 'ipv4_mask', 'ipv6_addr', 'ipv6_mask',
'ipv6_scope', 'state', 'mtu', 'metric', 'rx_packets', 'rx_errors', 'rx_dropped', 'rx_overruns',
'rx_frame', 'tx_packets', 'tx_errors', 'tx_dropped', 'tx_overruns', 'tx_carrier', 'tx_collisions',
'rx_bytes', 'tx_bytes']
def __init__(self, console_output):
"""
:param console_output:
"""
if isinstance(console_output, list):
source_data = " ".join(console_output)
else:
source_data = console_output.replace("\n", " ")
self.interfaces = self.parser(source_data=source_data)
def list_interfaces(self):
"""
:return:
"""
return sorted(self.interfaces.keys())
def count_interfaces(self):
"""
:return:
"""
return len(self.interfaces.keys())
def filter_interfaces(self, **kwargs):
"""
:param kwargs:
:return:
"""
for attr in kwargs.keys():
if attr not in IfconfigParser.attributes:
raise ValueError("Attribute [{}] not supported.".format(attr))
filtered_interfaces = []
for name, details in self.interfaces.items():
if all(getattr(details, attr) == kwargs[attr] for attr in kwargs.keys()):
filtered_interfaces.append(name)
return sorted(filtered_interfaces)
def get_interface(self, name):
"""
:param name:
:return:
"""
if name in self.list_interfaces():
return self.interfaces[name]
else:
raise InterfaceNotFound("Interface [{}] not found.".format(name))
def get_interfaces(self):
"""
:return:
"""
return self.interfaces
def is_available(self, name):
"""
:param name:
:return:
"""
return name in self.interfaces
def parser(self, source_data):
"""
:param source_data:
:return:
"""
# Linux syntax
re_linux_interface = re.compile(
r"(?P<name>[a-zA-Z0-9:._-]+)\s+Link encap:(?P<type>\S+\s?\S+)(\s+HWaddr\s+\b"
r"(?P<mac_addr>[0-9A-Fa-f:?]+))?",
re.I)
re_linux_ipv4 = re.compile(
r"inet addr:(?P<ipv4_addr>(?:[0-9]{1,3}\.){3}[0-9]{1,3})(\s+Bcast:"
r"(?P<ipv4_bcast>(?:[0-9]{1,3}\.){3}[0-9]{1,3}))?\s+Mask:(?P<ipv4_mask>(?:[0-9]{1,3}\.){3}[0-9]{1,3})",
re.I)
re_linux_ipv6 = re.compile(
r"inet6 addr:\s+(?P<ipv6_addr>\S+)/(?P<ipv6_mask>[0-9]+)\s+Scope:(?P<ipv6_scope>Link|Host)",
re.I)
re_linux_state = re.compile(
r"\W+(?P<state>(?:\w+\s)+)(?:\s+)?MTU:(?P<mtu>[0-9]+)\s+Metric:(?P<metric>[0-9]+)", re.I)
re_linux_rx = re.compile(
r"RX packets:(?P<rx_packets>[0-9]+)\s+errors:(?P<rx_errors>[0-9]+)\s+dropped:"
r"(?P<rx_dropped>[0-9]+)\s+overruns:(?P<rx_overruns>[0-9]+)\s+frame:(?P<rx_frame>[0-9]+)",
re.I)
re_linux_tx = re.compile(
r"TX packets:(?P<tx_packets>[0-9]+)\s+errors:(?P<tx_errors>[0-9]+)\s+dropped:"
r"(?P<tx_dropped>[0-9]+)\s+overruns:(?P<tx_overruns>[0-9]+)\s+carrier:(?P<tx_carrier>[0-9]+)",
re.I)
re_linux_bytes = re.compile(r"\W+RX bytes:(?P<rx_bytes>\d+)\s+\(.*\)\s+TX bytes:(?P<tx_bytes>\d+)\s+\(.*\)", re.I)
re_linux_tx_stats = re.compile(r"collisions:(?P<tx_collisions>[0-9]+)\s+txqueuelen:[0-9]+", re.I)
re_linux = [re_linux_interface, re_linux_ipv4, re_linux_ipv6, re_linux_state, re_linux_rx, re_linux_tx,
re_linux_bytes, re_linux_tx_stats]
# OpenBSD syntax
re_openbsd_interface = re.compile(
r"(?P<name>[a-zA-Z0-9:._-]+):\s+flags=(?P<flags>[0-9]+)<(?P<state>\S+)?>\s+mtu\s+(?P<mtu>[0-9]+)",
re.I)
re_openbsd_ipv4 = re.compile(
r"inet (?P<ipv4_addr>(?:[0-9]{1,3}\.){3}[0-9]{1,3})\s+netmask\s+"
r"(?P<ipv4_mask>(?:[0-9]{1,3}\.){3}[0-9]{1,3})(\s+broadcast\s+"
r"(?P<ipv4_bcast>(?:[0-9]{1,3}\.){3}[0-9]{1,3}))?",
re.I)
re_openbsd_ipv6 = re.compile(
r"inet6\s+(?P<ipv6_addr>\S+)\s+prefixlen\s+(?P<ipv6_mask>[0-9]+)\s+scopeid\s+(?P<ipv6_scope>\w+x\w+)<"
r"(?:link|host)>",
re.I)
re_openbsd_details = re.compile(
r"\S+\s+(?:(?P<mac_addr>[0-9A-Fa-f:?]+)\s+)?txqueuelen\s+[0-9]+\s+\((?P<type>\S+\s?\S+)\)", re.I)
re_openbsd_rx = re.compile(r"RX packets (?P<rx_packets>[0-9]+)\s+bytes\s+(?P<rx_bytes>\d+)\s+.*", re.I)
re_openbsd_rx_stats = re.compile(
r"RX errors (?P<rx_errors>[0-9]+)\s+dropped\s+(?P<rx_dropped>[0-9]+)\s+overruns\s+"
r"(?P<rx_overruns>[0-9]+)\s+frame\s+(?P<rx_frame>[0-9]+)",
re.I)
re_openbsd_tx = re.compile(r"TX packets (?P<tx_packets>[0-9]+)\s+bytes\s+(?P<tx_bytes>\d+)\s+.*", re.I)
re_openbsd_tx_stats = re.compile(
r"TX errors (?P<tx_errors>[0-9]+)\s+dropped\s+(?P<tx_dropped>[0-9]+)\s+overruns\s+"
r"(?P<tx_overruns>[0-9]+)\s+carrier\s+(?P<tx_carrier>[0-9]+)\s+collisions\s+(?P<tx_collisions>[0-9]+)",
re.I)
re_openbsd = [re_openbsd_interface, re_openbsd_ipv4, re_openbsd_ipv6, re_openbsd_details, re_openbsd_rx,
re_openbsd_rx_stats, re_openbsd_tx, re_openbsd_tx_stats]
# FreeBSD syntax
re_freebsd_interface = re.compile(
r"(?P<name>[a-zA-Z0-9:._-]+):\s+flags=(?P<flags>[0-9]+)<(?P<state>\S+)>\s+metric\s+"
r"(?P<metric>[0-9]+)\s+mtu\s+(?P<mtu>[0-9]+)",
re.I)
re_freebsd_ipv4 = re.compile(
r"inet (?P<ipv4_addr>(?:[0-9]{1,3}\.){3}[0-9]{1,3})\s+netmask\s+(?P<ipv4_mask>0x\S+)(\s+broadcast\s+"
r"(?P<ipv4_bcast>(?:[0-9]{1,3}\.){3}[0-9]{1,3}))?",
re.I)
re_freebsd_ipv6 = re.compile(r"\s?inet6\s(?P<ipv6_addr>.*)(?:\%\w+\d+)\sprefixlen\s(?P<ipv6_mask>\d+)(?:\s\w+)?\sscopeid\s(?P<ipv6_scope>\w+x\w+)", re.I)
re_freebsd_details = re.compile(r"ether\s+(?P<mac_addr>[0-9A-Fa-f:?]+)", re.I)
re_freebsd = [re_freebsd_interface, re_freebsd_ipv4, re_freebsd_ipv6, re_freebsd_details]
available_interfaces = dict()
for pattern in [re_linux_interface, re_openbsd_interface, re_freebsd_interface]:
network_interfaces = re.finditer(pattern, source_data)
positions = []
while True:
try:
pos = next(network_interfaces)
positions.append(max(pos.start() - 1, 0))
except StopIteration:
break
if positions:
positions.append(len(source_data))
break
if not positions:
return available_interfaces
for l, r in zip(positions, positions[1:]):
chunk = source_data[l:r]
_interface = dict()
for pattern in re_linux + re_openbsd + re_freebsd:
match = re.search(pattern, chunk.replace('\t', '\n'))
if match:
details = match.groupdict()
for k, v in details.items():
if isinstance(v, str): details[k] = v.strip()
_interface.update(details)
if _interface is not None:
available_interfaces[_interface['name']] = self.update_interface_details(_interface)
return available_interfaces
@staticmethod
def update_interface_details(interface):
for attr in IfconfigParser.attributes:
if attr not in interface:
interface[attr] = None
return namedtuple('Interface', interface.keys())(**interface)
class InterfaceNotFound(Exception):
"""
"""
pass
def process(proc_data):
"""
Final processing to conform to the schema.
@@ -220,7 +415,7 @@ def process(proc_data):
# convert OSX-style subnet mask to dotted quad
if 'ipv4_mask' in entry:
try:
if entry['ipv4_mask'].find('0x') == 0:
if entry['ipv4_mask'].startswith('0x'):
new_mask = entry['ipv4_mask']
new_mask = new_mask.lstrip('0x')
new_mask = '.'.join(str(int(i, 16)) for i in [new_mask[i:i + 2] for i in range(0, len(new_mask), 2)])

View File

@@ -134,7 +134,7 @@ import jc.utils
class info():
version = '1.1'
version = '1.2'
description = 'iptables command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -247,7 +247,7 @@ def parse(data, raw=False, quiet=False):
for line in cleandata:
if line.find('Chain') == 0:
if line.startswith('Chain'):
raw_output.append(chain)
chain = {}
headers = []
@@ -259,7 +259,7 @@ def parse(data, raw=False, quiet=False):
continue
elif line.find('target') == 0 or line.find('pkts') == 1 or line.find('num') == 0:
elif line.startswith('target') or line.find('pkts') == 1 or line.startswith('num'):
headers = []
headers = [h for h in ' '.join(line.lower().strip().split()).split() if h]
headers.append("options")

View File

@@ -77,7 +77,7 @@ import jc.utils
class info():
version = '1.0'
version = '1.1'
description = 'jobs command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -176,11 +176,11 @@ def parse(data, raw=False, quiet=False):
parsed_line.insert(0, job_number)
# check for + or - in first field
if parsed_line[0].find('+') != -1:
if '+' in parsed_line[0]:
job_history = 'current'
parsed_line[0] = parsed_line[0].rstrip('+')
if parsed_line[0].find('-') != -1:
if '-' in parsed_line[0]:
job_history = 'previous'
parsed_line[0] = parsed_line[0].rstrip('-')

181
jc/parsers/last.py Normal file
View File

@@ -0,0 +1,181 @@
"""jc - JSON CLI output utility last Parser
Usage:
specify --last as the first argument if the piped input is coming from last or lastb
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ last | jc --last -p
[
{
"user": "kbrazil",
"tty": "ttys002",
"hostname": null,
"login": "Thu Feb 27 14:31",
"logout": "still logged in"
},
{
"user": "kbrazil",
"tty": "ttys003",
"hostname": null,
"login": "Thu Feb 27 10:38",
"logout": "10:38",
"duration": "00:00"
},
{
"user": "kbrazil",
"tty": "ttys003",
"hostname": null,
"login": "Thu Feb 27 10:18",
"logout": "10:18",
"duration": "00:00"
},
...
]
$ last | jc --last -p -r
[
{
"user": "kbrazil",
"tty": "ttys002",
"hostname": "-",
"login": "Thu Feb 27 14:31",
"logout": "still_logged_in"
},
{
"user": "kbrazil",
"tty": "ttys003",
"hostname": "-",
"login": "Thu Feb 27 10:38",
"logout": "10:38",
"duration": "00:00"
},
{
"user": "kbrazil",
"tty": "ttys003",
"hostname": "-",
"login": "Thu Feb 27 10:18",
"logout": "10:18",
"duration": "00:00"
},
...
]
"""
import re
import jc.utils
class info():
version = '1.0'
description = 'last and lastb 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 = ['last', 'lastb']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"user": string,
"tty": string,
"hostname": string,
"login": string,
"logout": string,
"duration": string
}
]
"""
for entry in proc_data:
if 'tty' in entry and entry['tty'] == '~':
entry['tty'] = None
if 'tty' in entry and entry['tty'] == 'system_boot':
entry['tty'] = 'system boot'
if 'hostname' in entry and entry['hostname'] == '-':
entry['hostname'] = None
if 'logout' in entry and entry['logout'] == 'still_logged_in':
entry['logout'] = 'still logged in'
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
cleandata = data.splitlines()
# Clear any blank lines
cleandata = list(filter(None, cleandata))
if cleandata:
for entry in cleandata:
output_line = {}
if entry.startswith('wtmp begins ') or entry.startswith('btmp begins '):
continue
entry = entry.replace('system boot', 'system_boot')
entry = entry.replace(' still logged in', '- still_logged_in')
linedata = entry.split()
if re.match(r'[MTWFS][ouerha][nedritnu] [JFMASOND][aepuco][nbrynlgptvc]', ' '.join(linedata[2:4])):
linedata.insert(2, '-')
output_line['user'] = linedata[0]
output_line['tty'] = linedata[1]
output_line['hostname'] = linedata[2]
output_line['login'] = ' '.join(linedata[3:7])
if len(linedata) > 8:
output_line['logout'] = linedata[8]
if len(linedata) > 9:
output_line['duration'] = linedata[9].replace('(', '').replace(')', '')
raw_output.append(output_line)
if raw:
return raw_output
else:
return process(raw_output)

View File

@@ -1,16 +1,20 @@
"""jc - JSON CLI output utility ls Parser
Note: The -l or -b option of ls should be used to correctly parse filenames that include newline characters.
Since ls does not encode newlines in filenames when outputting to a pipe it will cause jc to see
multiple files instead of a single file if -l or -b is not used.
Usage:
specify --ls as the first argument if the piped input is coming from ls
ls options supported:
- None
- laR
-lbaR
--time-style=full-iso
- h file sizes will be available in text form with -r but larger file sizes
with human readable suffixes will be converted to Null in default view
since the parser attempts to convert this field to an integer.
-h file sizes will be available in text form with -r but larger file sizes
with human readable suffixes will be converted to Null in default view
since the parser attempts to convert this field to an integer.
Compatibility:
@@ -145,7 +149,7 @@ import jc.utils
class info():
version = '1.1'
version = '1.3'
description = 'ls command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -215,19 +219,20 @@ def parse(data, raw=False, quiet=False):
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
warned = False
parent = ''
next_is_parent = False
new_section = False
linedata = data.splitlines()
# Delete first line if it starts with 'total 1234'
if linedata:
if re.match('^total [0-9]+', linedata[0]):
if re.match(r'total [0-9]+', linedata[0]):
linedata.pop(0)
parent = ''
next_is_parent = False
# Look for parent line if glob or -R is used
if not re.match('^[-dclpsbDCMnP?]([-r][-w][-xsS]){2}([-r][-w][-xtT])[+]?', linedata[0]) \
if not re.match(r'[-dclpsbDCMnP?]([-r][-w][-xsS]){2}([-r][-w][-xtT])[+]?', linedata[0]) \
and linedata[0].endswith(':'):
parent = linedata.pop(0)[:-1]
# Pop following total line
@@ -235,25 +240,42 @@ def parse(data, raw=False, quiet=False):
if linedata:
# Check if -l was used to parse extra data
if re.match('^[-dclpsbDCMnP?]([-r][-w][-xsS]){2}([-r][-w][-xtT])[+]?', linedata[0]):
if re.match(r'[-dclpsbDCMnP?]([-r][-w][-xsS]){2}([-r][-w][-xtT])[+]?', linedata[0]):
for entry in linedata:
output_line = {}
parsed_line = entry.split(maxsplit=8)
if not re.match('^[-dclpsbDCMnP?]([-r][-w][-xsS]){2}([-r][-w][-xtT])[+]?', entry) \
if not re.match(r'[-dclpsbDCMnP?]([-r][-w][-xsS]){2}([-r][-w][-xtT])[+]?', entry) \
and entry.endswith(':'):
parent = entry[:-1]
new_section = True
# fixup to remove trailing \n in previous entry
raw_output[-1]['filename'] = raw_output[-1]['filename'][:-1]
continue
if re.match('^total [0-9]+', entry):
if re.match(r'total [0-9]+', entry):
new_section = False
continue
if entry == '':
# fix for OSX - doesn't print 'total xx' line if empty directory
if new_section and entry == '':
new_section = False
continue
# fixup for filenames with newlines
if not new_section \
and not re.match(r'[-dclpsbDCMnP?]([-r][-w][-xsS]){2}([-r][-w][-xtT])[+]?', entry):
raw_output[-1]['filename'] = raw_output[-1]['filename'] + '\n' + entry
continue
# split filenames and links
filename_field = parsed_line[8].split(' -> ')
if len(parsed_line) == 9:
filename_field = parsed_line[8].split(' -> ')
else:
# in case of filenames starting with a newline character
filename_field = ['']
# create list of dictionaries
output_line['filename'] = filename_field[0]
@@ -279,11 +301,15 @@ def parse(data, raw=False, quiet=False):
next_is_parent = True
continue
if next_is_parent:
if next_is_parent and entry.endswith(':'):
parent = entry[:-1]
next_is_parent = False
continue
if not quiet and next_is_parent and not entry.endswith(':') and not warned:
jc.utils.warning_message('Newline characters detected. Filenames probably corrupted. Use ls -l or -b instead.')
warned = True
output_line['filename'] = entry
if parent:

View File

@@ -97,7 +97,7 @@ import jc.parsers.universal
class info():
version = '1.0'
version = '1.1'
description = 'lsof command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -180,47 +180,6 @@ def parse(data, raw=False, quiet=False):
raw_output = jc.parsers.universal.sparse_table_parse(cleandata)
'''
# find column value of last character of each header
header_text = cleandata.pop(0).lower()
# clean up 'size/off' header
# even though forward slash in a key is valid json, it can make things difficult
header_row = header_text.replace('/', '_')
headers = header_row.split()
header_spec = []
for i, h in enumerate(headers):
# header tuple is (index, header_name, col)
header_spec.append((i, h, header_row.find(h) + len(h)))
# parse lines
for entry in cleandata:
output_line = {}
# normalize data by inserting Null for missing data
temp_line = entry.split(maxsplit=len(headers) - 1)
for spec in header_spec:
index = spec[0]
header_name = spec[1]
col = spec[2] - 1 # subtract one since column starts at 0 instead of 1
if header_name == 'command' or header_name == 'name':
continue
if entry[col] in string.whitespace:
temp_line.insert(index, None)
name = ' '.join(temp_line[9:])
fixed_line = temp_line[0:9]
fixed_line.append(name)
output_line = dict(zip(headers, fixed_line))
raw_output.append(output_line)
'''
if raw:
return raw_output
else:

View File

@@ -56,7 +56,7 @@ import jc.utils
class info():
version = '1.1'
version = '1.2'
description = 'mount command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -165,7 +165,7 @@ def parse(data, raw=False, quiet=False):
if cleandata:
# check for OSX output
if cleandata[0].find(' type ') == -1:
if ' type ' not in cleandata[0]:
raw_output = osx_parse(cleandata)
else:

View File

@@ -313,7 +313,7 @@ import jc.utils
class info():
version = '1.2'
version = '1.3'
description = 'netstat command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -498,14 +498,14 @@ def parse_post(raw_data):
if 'proto' in entry and 'kind' in entry:
if entry['kind'] == 'network':
if entry['proto'].find('tcp') != -1:
if 'tcp' in entry['proto']:
entry['transport_protocol'] = 'tcp'
elif entry['proto'].find('udp') != -1:
elif 'udp' in entry['proto']:
entry['transport_protocol'] = 'udp'
else:
entry['transport_protocol'] = None
if entry['proto'].find('6') != -1:
if '6' in entry['proto']:
entry['network_protocol'] = 'ipv6'
else:
entry['network_protocol'] = 'ipv4'
@@ -542,19 +542,19 @@ def parse(data, raw=False, quiet=False):
for line in cleandata:
if line.find('Active Internet') == 0:
if line.startswith('Active Internet'):
network_list = []
network = True
socket = False
continue
if line.find('Active UNIX') == 0:
if line.startswith('Active UNIX'):
socket_list = []
network = False
socket = True
continue
if line.find('Proto') == 0:
if line.startswith('Proto'):
header_text = normalize_headers(line)
headers = header_text.split()
continue

297
jc/parsers/ntpq.py Normal file
View File

@@ -0,0 +1,297 @@
"""jc - JSON CLI output utility ntpq Parser
Usage:
specify --ntpq as the first argument if the piped input is coming from ntpq -p
Compatibility:
'linux'
Examples:
$ ntpq -p | jc --ntpq -p
[
{
"remote": "44.190.6.254",
"refid": "127.67.113.92",
"st": 2,
"t": "u",
"when": 1,
"poll": 64,
"reach": 1,
"delay": 23.399,
"offset": -2.805,
"jitter": 2.131,
"state": null
},
{
"remote": "ntp.wdc1.us.lea",
"refid": "130.133.1.10",
"st": 2,
"t": "u",
"when": null,
"poll": 64,
"reach": 1,
"delay": 93.053,
"offset": -0.807,
"jitter": 2.839,
"state": null
},
{
"remote": "clock.team-cymr",
"refid": "204.9.54.119",
"st": 2,
"t": "u",
"when": null,
"poll": 64,
"reach": 1,
"delay": 70.337,
"offset": -2.909,
"jitter": 2.6,
"state": null
},
{
"remote": "mirror1.sjc02.s",
"refid": "216.218.254.202",
"st": 2,
"t": "u",
"when": 2,
"poll": 64,
"reach": 1,
"delay": 29.325,
"offset": 1.044,
"jitter": 4.069,
"state": null,
}
]
$ ntpq -pn| jc --ntpq -p
[
{
"remote": "44.190.6.254",
"refid": "127.67.113.92",
"st": 2,
"t": "u",
"when": 66,
"poll": 64,
"reach": 377,
"delay": 22.69,
"offset": -0.392,
"jitter": 2.085,
"state": "+"
},
{
"remote": "108.59.2.24",
"refid": "130.133.1.10",
"st": 2,
"t": "u",
"when": 63,
"poll": 64,
"reach": 377,
"delay": 90.805,
"offset": 2.84,
"jitter": 1.908,
"state": "-"
},
{
"remote": "38.229.71.1",
"refid": "204.9.54.119",
"st": 2,
"t": "u",
"when": 64,
"poll": 64,
"reach": 377,
"delay": 68.699,
"offset": -0.61,
"jitter": 2.576,
"state": "+"
},
{
"remote": "72.5.72.15",
"refid": "216.218.254.202",
"st": 2,
"t": "u",
"when": 63,
"poll": 64,
"reach": 377,
"delay": 22.654,
"offset": 0.231,
"jitter": 1.964,
"state": "*"
}
]
$ ntpq -pn| jc --ntpq -p -r
[
{
"s": "+",
"remote": "44.190.6.254",
"refid": "127.67.113.92",
"st": "2",
"t": "u",
"when": "66",
"poll": "64",
"reach": "377",
"delay": "22.690",
"offset": "-0.392",
"jitter": "2.085"
},
{
"s": "-",
"remote": "108.59.2.24",
"refid": "130.133.1.10",
"st": "2",
"t": "u",
"when": "63",
"poll": "64",
"reach": "377",
"delay": "90.805",
"offset": "2.840",
"jitter": "1.908"
},
{
"s": "+",
"remote": "38.229.71.1",
"refid": "204.9.54.119",
"st": "2",
"t": "u",
"when": "64",
"poll": "64",
"reach": "377",
"delay": "68.699",
"offset": "-0.610",
"jitter": "2.576"
},
{
"s": "*",
"remote": "72.5.72.15",
"refid": "216.218.254.202",
"st": "2",
"t": "u",
"when": "63",
"poll": "64",
"reach": "377",
"delay": "22.654",
"offset": "0.231",
"jitter": "1.964"
}
]
"""
import jc.utils
import jc.parsers.universal
class info():
version = '1.0'
description = 'ntpq -p command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
# compatible options: linux, darwin, cygwin, win32, aix, freebsd
compatible = ['linux']
magic_commands = ['ntpq']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"state": string, # space/~ converted to null
"remote": string,
"refid": string,
"st": integer,
"t": string,
"when": integer, # - converted to null
"poll": integer,
"reach": integer,
"delay": float,
"offset": float,
"jitter": float
},
]
"""
for entry in proc_data:
if entry['s'] == '~':
entry['s'] = None
entry['state'] = entry.pop('s')
int_list = ['st', 'when', 'poll', 'reach']
for key in int_list:
if key in entry:
try:
entry[key] = int(entry[key])
except (ValueError):
entry[key] = None
float_list = ['delay', 'offset', 'jitter']
for key in float_list:
if key in entry:
try:
entry[key] = float(entry[key])
except (ValueError):
entry[key] = None
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
cleandata = data.splitlines()
cleandata[0] = 's ' + cleandata[0]
cleandata[0] = cleandata[0].lower()
# delete header delimiter
del cleandata[1]
# separate first character with a space for easier parsing
for i, line in list(enumerate(cleandata[1:])):
if line[0] == ' ':
# fixup for no-state
cleandata[i + 1] = '~ ' + line[1:]
else:
# fixup - realign columns since we added the 's' column
cleandata[i + 1] = line[:1] + ' ' + line[1:]
# fixup for occaisional ip/hostname fields with a space
cleandata[i + 1] = cleandata[i + 1].replace(' (', '_(')
raw_output = jc.parsers.universal.simple_table_parse(cleandata)
if raw:
return raw_output
else:
return process(raw_output)

175
jc/parsers/passwd.py Normal file
View File

@@ -0,0 +1,175 @@
"""jc - JSON CLI output utility /etc/passwd file Parser
Usage:
specify --passwd as the first argument if the piped input is coming from /etc/passwd
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ cat /etc/passwd | jc --passwd -p
[
{
"username": "nobody",
"password": "*",
"uid": -2,
"gid": -2,
"comment": "Unprivileged User",
"home": "/var/empty",
"shell": "/usr/bin/false"
},
{
"username": "root",
"password": "*",
"uid": 0,
"gid": 0,
"comment": "System Administrator",
"home": "/var/root",
"shell": "/bin/sh"
},
{
"username": "daemon",
"password": "*",
"uid": 1,
"gid": 1,
"comment": "System Services",
"home": "/var/root",
"shell": "/usr/bin/false"
},
...
]
$ cat /etc/passwd | jc --passwd -p -r
[
{
"username": "nobody",
"password": "*",
"uid": "-2",
"gid": "-2",
"comment": "Unprivileged User",
"home": "/var/empty",
"shell": "/usr/bin/false"
},
{
"username": "root",
"password": "*",
"uid": "0",
"gid": "0",
"comment": "System Administrator",
"home": "/var/root",
"shell": "/bin/sh"
},
{
"username": "daemon",
"password": "*",
"uid": "1",
"gid": "1",
"comment": "System Services",
"home": "/var/root",
"shell": "/usr/bin/false"
},
...
]
"""
import jc.utils
class info():
version = '1.0'
description = '/etc/passwd file 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']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"username": string,
"password": string,
"uid": integer,
"gid": integer,
"comment": string,
"home": string,
"shell": string
}
]
"""
for entry in proc_data:
int_list = ['uid', 'gid']
for key in int_list:
if key in entry:
try:
key_int = int(entry[key])
entry[key] = key_int
except (ValueError):
entry[key] = None
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
cleandata = data.splitlines()
# Clear any blank lines
cleandata = list(filter(None, cleandata))
if cleandata:
for entry in cleandata:
if entry.startswith('#'):
continue
output_line = {}
fields = entry.split(':')
output_line['username'] = fields[0]
output_line['password'] = fields[1]
output_line['uid'] = fields[2]
output_line['gid'] = fields[3]
output_line['comment'] = fields[4]
output_line['home'] = fields[5]
output_line['shell'] = fields[6]
raw_output.append(output_line)
if raw:
return raw_output
else:
return process(raw_output)

View File

@@ -32,7 +32,7 @@ import jc.parsers.universal
class info():
version = '1.0'
version = '1.1'
description = 'pip list command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -94,7 +94,7 @@ def parse(data, raw=False, quiet=False):
cleandata = list(filter(None, linedata))
# detect legacy output type
if cleandata[0].find(' (') != -1:
if ' (' in cleandata[0]:
for row in cleandata:
raw_output.append({'package': row.split(' (')[0],
'version': row.split(' (')[1].rstrip(')')})
@@ -103,7 +103,7 @@ def parse(data, raw=False, quiet=False):
else:
# clear separator line
for i, line in reversed(list(enumerate(cleandata))):
if line.find('---') != -1:
if '---' in line:
cleandata.pop(i)
cleandata[0] = cleandata[0].lower()

183
jc/parsers/shadow.py Normal file
View File

@@ -0,0 +1,183 @@
"""jc - JSON CLI output utility /etc/shadow file Parser
Usage:
specify --shadow as the first argument if the piped input is coming from /etc/shadow
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ sudo cat /etc/shadow | jc --shadow -p
[
{
"username": "root",
"password": "*",
"last_changed": 18113,
"minimum": 0,
"maximum": 99999,
"warn": 7,
"inactive": null,
"expire": null
},
{
"username": "daemon",
"password": "*",
"last_changed": 18113,
"minimum": 0,
"maximum": 99999,
"warn": 7,
"inactive": null,
"expire": null
},
{
"username": "bin",
"password": "*",
"last_changed": 18113,
"minimum": 0,
"maximum": 99999,
"warn": 7,
"inactive": null,
"expire": null
},
...
]
$ sudo cat /etc/shadow | jc --shadow -p -r
[
{
"username": "root",
"password": "*",
"last_changed": "18113",
"minimum": "0",
"maximum": "99999",
"warn": "7",
"inactive": "",
"expire": ""
},
{
"username": "daemon",
"password": "*",
"last_changed": "18113",
"minimum": "0",
"maximum": "99999",
"warn": "7",
"inactive": "",
"expire": ""
},
{
"username": "bin",
"password": "*",
"last_changed": "18113",
"minimum": "0",
"maximum": "99999",
"warn": "7",
"inactive": "",
"expire": ""
},
...
]
"""
import jc.utils
class info():
version = '1.0'
description = '/etc/shadow file 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']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"username": string,
"password": string,
"last_changed": integer,
"minimum": integer,
"maximum": integer,
"warn": integer,
"inactive": integer,
"expire": integer
}
]
"""
for entry in proc_data:
int_list = ['last_changed', 'minimum', 'maximum', 'warn', 'inactive', 'expire']
for key in int_list:
if key in entry:
try:
key_int = int(entry[key])
entry[key] = key_int
except (ValueError):
entry[key] = None
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
cleandata = data.splitlines()
# Clear any blank lines
cleandata = list(filter(None, cleandata))
if cleandata:
for entry in cleandata:
if entry.startswith('#'):
continue
output_line = {}
fields = entry.split(':')
output_line['username'] = fields[0]
output_line['password'] = fields[1]
output_line['last_changed'] = fields[2]
output_line['minimum'] = fields[3]
output_line['maximum'] = fields[4]
output_line['warn'] = fields[5]
output_line['inactive'] = fields[6]
output_line['expire'] = fields[7]
raw_output.append(output_line)
if raw:
return raw_output
else:
return process(raw_output)

View File

@@ -104,7 +104,7 @@ import jc.utils
class info():
version = '1.0'
version = '1.1'
description = 'stat command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -208,7 +208,7 @@ def parse(data, raw=False, quiet=False):
output_line['file'] = line_list[1]
# populate link_to field if -> found
if output_line['file'].find(' -> ') != -1:
if ' -> ' in output_line['file']:
filename = output_line['file'].split(' -> ')[0].strip('\u2018').rstrip('\u2019')
link = output_line['file'].split(' -> ')[1].strip('\u2018').rstrip('\u2019')
output_line['file'] = filename
@@ -229,7 +229,7 @@ def parse(data, raw=False, quiet=False):
continue
# line #3
if line.find('Device:') == 0:
if line.startswith('Device:'):
line_list = line.split()
output_line['device'] = line_list[1]
output_line['inode'] = line_list[3]
@@ -237,7 +237,7 @@ def parse(data, raw=False, quiet=False):
continue
# line #4
if line.find('Access: (') == 0:
if line.startswith('Access: ('):
line = line.replace('(', ' ').replace(')', ' ').replace('/', ' ')
line_list = line.split()
output_line['access'] = line_list[1]
@@ -249,19 +249,19 @@ def parse(data, raw=False, quiet=False):
continue
# line #5
if line.find('Access: 2') == 0:
if line.startswith('Access: 2'):
line_list = line.split(maxsplit=1)
output_line['access_time'] = line_list[1]
continue
# line #6
if line.find('Modify:') == 0:
if line.startswith('Modify:'):
line_list = line.split(maxsplit=1)
output_line['modify_time'] = line_list[1]
continue
# line #7
if line.find('Change:') == 0:
if line.startswith('Change:'):
line_list = line.split(maxsplit=1)
output_line['change_time'] = line_list[1]
continue

View File

@@ -40,7 +40,7 @@ import jc.utils
class info():
version = '1.0'
version = '1.1'
description = 'systemctl command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -110,7 +110,7 @@ def parse(data, raw=False, quiet=False):
raw_output = []
for entry in cleandata[1:]:
if entry.find('LOAD = ') != -1:
if 'LOAD = ' in entry:
break
else:

View File

@@ -59,7 +59,7 @@ import jc.utils
class info():
version = '1.0'
version = '1.1'
description = 'systemctl list-jobs command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -137,7 +137,7 @@ def parse(data, raw=False, quiet=False):
raw_output = []
for entry in cleandata[1:]:
if entry.find('No jobs running.') != -1 or entry.find('jobs listed.') != -1:
if 'No jobs running.' in entry or 'jobs listed.' in entry:
break
else:

View File

@@ -34,7 +34,7 @@ import jc.utils
class info():
version = '1.0'
version = '1.1'
description = 'systemctl list-sockets command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -102,7 +102,7 @@ def parse(data, raw=False, quiet=False):
raw_output = []
for entry in cleandata[1:]:
if entry.find('sockets listed.') != -1:
if 'sockets listed.' in entry:
break
else:

View File

@@ -31,7 +31,7 @@ import jc.utils
class info():
version = '1.0'
version = '1.1'
description = 'systemctl list-unit-files command parser'
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
@@ -99,7 +99,7 @@ def parse(data, raw=False, quiet=False):
raw_output = []
for entry in cleandata[1:]:
if entry.find('unit files listed.') != -1:
if 'unit files listed.' in entry:
break
else:

122
jc/parsers/timedatectl.py Normal file
View File

@@ -0,0 +1,122 @@
"""jc - JSON CLI output utility timedatectl Parser
Usage:
specify --timedatectl as the first argument if the piped input is coming from timedatectl or timedatectl status
Compatibility:
'linux'
Examples:
$ timedatectl | jc --timedatectl -p
{
"local_time": "Tue 2020-03-10 17:53:21 PDT",
"universal_time": "Wed 2020-03-11 00:53:21 UTC",
"rtc_time": "Wed 2020-03-11 00:53:21",
"time_zone": "America/Los_Angeles (PDT, -0700)",
"ntp_enabled": true,
"ntp_synchronized": true,
"rtc_in_local_tz": false,
"dst_active": true
}
$ timedatectl | jc --timedatectl -p -r
{
"local_time": "Tue 2020-03-10 17:53:21 PDT",
"universal_time": "Wed 2020-03-11 00:53:21 UTC",
"rtc_time": "Wed 2020-03-11 00:53:21",
"time_zone": "America/Los_Angeles (PDT, -0700)",
"ntp_enabled": "yes",
"ntp_synchronized": "yes",
"rtc_in_local_tz": "no",
"dst_active": "yes"
}
"""
import jc.utils
class info():
version = '1.0'
description = 'timedatectl status 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']
magic_commands = ['timedatectl', 'timedatectl status']
__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:
{
"local_time": string,
"universal_time": string,
"rtc_time": string,
"time_zone": string,
"ntp_enabled": boolean,
"ntp_synchronized": boolean,
"system_clock_synchronized": boolean,
"systemd-timesyncd.service_active": boolean,
"rtc_in_local_tz": boolean,
"dst_active": boolean
}
"""
# boolean changes
bool_list = ['ntp_enabled', 'ntp_synchronized', 'rtc_in_local_tz', 'dst_active',
'system_clock_synchronized', 'systemd-timesyncd.service_active']
for key in proc_data:
if key in bool_list:
try:
proc_data[key] = True if proc_data[key] == 'yes' else False
except (ValueError):
proc_data[key] = None
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 = {}
for line in filter(None, data.splitlines()):
linedata = line.split(':', maxsplit=1)
raw_output[linedata[0].strip().lower().replace(' ', '_')] = linedata[1].strip()
if linedata[0].strip() == 'DST active':
break
if raw:
return raw_output
else:
return process(raw_output)

284
jc/parsers/who.py Normal file
View File

@@ -0,0 +1,284 @@
"""jc - JSON CLI output utility who Parser
Usage:
specify --who as the first argument if the piped input is coming from who
accepts any of the following who options (or no options): -aTH
Compatibility:
'linux', 'darwin', 'cygwin', 'aix', 'freebsd'
Examples:
$ who -a | jc --who -p
[
{
"event": "reboot",
"time": "Feb 7 23:31",
"pid": 1
},
{
"user": "joeuser",
"writeable_tty": "-",
"tty": "console",
"time": "Feb 7 23:32",
"idle": "old",
"pid": 105
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys000",
"time": "Feb 13 16:44",
"idle": ".",
"pid": 51217,
"comment": "term=0 exit=0"
},
{
"user": "joeuser",
"writeable_tty": "?",
"tty": "ttys003",
"time": "Feb 28 08:59",
"idle": "01:36",
"pid": 41402
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys004",
"time": "Mar 1 16:35",
"idle": ".",
"pid": 15679,
"from": "192.168.1.5"
}
]
$ who -a | jc --who -p -r
[
{
"event": "reboot",
"time": "Feb 7 23:31",
"pid": "1"
},
{
"user": "joeuser",
"writeable_tty": "-",
"tty": "console",
"time": "Feb 7 23:32",
"idle": "old",
"pid": "105"
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys000",
"time": "Feb 13 16:44",
"idle": ".",
"pid": "51217",
"comment": "term=0 exit=0"
},
{
"user": "joeuser",
"writeable_tty": "?",
"tty": "ttys003",
"time": "Feb 28 08:59",
"idle": "01:36",
"pid": "41402"
},
{
"user": "joeuser",
"writeable_tty": "+",
"tty": "ttys004",
"time": "Mar 1 16:35",
"idle": ".",
"pid": "15679",
"from": "192.168.1.5"
}
]
"""
import re
import jc.utils
class info():
version = '1.0'
description = 'who 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', 'cygwin', 'aix', 'freebsd']
magic_commands = ['who']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"user": string,
"event": string,
"writeable_tty": string,
"tty": string,
"time": string,
"idle": string,
"pid": integer,
"from": string,
"comment": string
}
]
"""
for entry in proc_data:
int_list = ['pid']
for key in int_list:
if key in entry:
try:
key_int = int(entry[key])
entry[key] = key_int
except (ValueError):
entry[key] = None
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:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
cleandata = data.splitlines()
# Clear any blank lines
cleandata = list(filter(None, cleandata))
if cleandata:
for line in cleandata:
output_line = {}
linedata = line.split()
# clear headers, if they exist
if ''.join(linedata[0:3]) == 'NAMELINETIME' \
or ''.join(linedata[0:3]) == 'USERLINEWHEN':
linedata.pop(0)
continue
# mac reboot line
if linedata[0] == 'reboot':
output_line['event'] = 'reboot'
output_line['time'] = ' '.join(linedata[2:5])
output_line['pid'] = linedata[6]
raw_output.append(output_line)
continue
# linux reboot line
if ''.join(linedata[0:2]) == 'systemboot':
output_line['event'] = 'reboot'
output_line['time'] = ' '.join(linedata[2:4])
raw_output.append(output_line)
continue
# linux login line
if linedata[0] == 'LOGIN':
output_line['event'] = 'login'
output_line['tty'] = linedata[1]
output_line['time'] = ' '.join(linedata[2:4])
output_line['pid'] = linedata[4]
if len(linedata) > 5:
output_line['comment'] = ' '.join(linedata[5:])
raw_output.append(output_line)
continue
# linux run-level
if linedata[0] == 'run-level':
output_line['event'] = ' '.join(linedata[0:2])
output_line['time'] = ' '.join(linedata[2:4])
raw_output.append(output_line)
continue
# mac run-level (ignore because not enough useful info)
if linedata[1] == 'run-level':
continue
# pts lines with no user information
if linedata[0].startswith('pts/'):
output_line['tty'] = linedata[0]
output_line['time'] = ' '.join(linedata[1:3])
output_line['pid'] = linedata[3]
output_line['comment'] = ' '.join(linedata[4:])
raw_output.append(output_line)
continue
# user logins
output_line['user'] = linedata.pop(0)
if linedata[0] in '+-?':
output_line['writeable_tty'] = linedata.pop(0)
output_line['tty'] = linedata.pop(0)
# mac
if re.match(r'[JFMASOND][aepuco][nbrynlgptvc]', linedata[0]):
output_line['time'] = ' '.join([linedata.pop(0),
linedata.pop(0),
linedata.pop(0)])
# linux
else:
output_line['time'] = ' '.join([linedata.pop(0),
linedata.pop(0)])
# if just one more field, then it's the remote IP
if len(linedata) == 1:
output_line['from'] = linedata[0].replace('(', '').replace(')', '')
raw_output.append(output_line)
continue
# extended info: idle
if len(linedata) > 0:
output_line['idle'] = linedata.pop(0)
# extended info: pid
if len(linedata) > 0:
output_line['pid'] = linedata.pop(0)
# extended info is from
if len(linedata) > 0 and linedata[0].startswith('('):
output_line['from'] = linedata[0].replace('(', '').replace(')', '')
# else, extended info is comment
elif len(linedata) > 0:
output_line['comment'] = ' '.join(linedata)
raw_output.append(output_line)
if raw:
return raw_output
else:
return process(raw_output)

3
requirements.txt Normal file
View File

@@ -0,0 +1,3 @@
ruamel.yaml>=0.15.0
xmltodict>=0.12.0
Pygments>=2.4.2

2
setup.cfg Normal file
View File

@@ -0,0 +1,2 @@
[metadata]
license_file = LICENSE.md

View File

@@ -5,22 +5,21 @@ with open('README.md', 'r') as f:
setuptools.setup(
name='jc',
version='1.7.4',
version='1.10.8',
author='Kelly Brazil',
author_email='kellyjonbrazil@gmail.com',
description='This tool serializes the output of popular command line tools and filetypes to structured JSON output.',
install_requires=[
'ifconfig-parser>=0.0.5',
'ruamel.yaml>=0.15.0',
'xmltodict>=0.12.0'
'xmltodict>=0.12.0',
'Pygments>=2.4.2'
],
license='MIT',
long_description=long_description,
long_description_content_type='text/markdown',
python_requires='>=3.6',
url='https://github.com/kellyjonbrazil/jc',
packages=setuptools.find_packages(),
include_package_data=True,
packages=setuptools.find_packages(exclude=['*.tests', '*.tests.*', 'tests.*', 'tests']),
entry_points={
'console_scripts': [
'jc=jc.cli:main'

View File

@@ -0,0 +1 @@
[{"uuid": "3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM", "version": "LVM2 001", "type": "LVM2_member", "usage": "raid", "minimum_io_size": 512, "physical_sector_size": 512, "logical_sector_size": 512, "part_entry_scheme": "dos", "part_entry_type": "0x8e", "part_entry_number": 2, "part_entry_offset": 2099200, "part_entry_size": 39843840, "part_entry_disk": "8:0", "device": "/dev/sda2"}, {"uuid": "05d927bb-5875-49e3-ada1-7f46cb31c932", "type": "xfs", "usage": "filesystem", "minimum_io_size": 512, "physical_sector_size": 512, "logical_sector_size": 512, "part_entry_scheme": "dos", "part_entry_type": "0x83", "part_entry_flags": "0x80", "part_entry_number": 1, "part_entry_offset": 2048, "part_entry_size": 2097152, "part_entry_disk": "8:0", "device": "/dev/sda1"}]

View File

@@ -0,0 +1,29 @@
DEVNAME=/dev/sda2
UUID=3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM
VERSION=LVM2 001
TYPE=LVM2_member
USAGE=raid
MINIMUM_IO_SIZE=512
PHYSICAL_SECTOR_SIZE=512
LOGICAL_SECTOR_SIZE=512
PART_ENTRY_SCHEME=dos
PART_ENTRY_TYPE=0x8e
PART_ENTRY_NUMBER=2
PART_ENTRY_OFFSET=2099200
PART_ENTRY_SIZE=39843840
PART_ENTRY_DISK=8:0
DEVNAME=/dev/sda1
UUID=05d927bb-5875-49e3-ada1-7f46cb31c932
TYPE=xfs
USAGE=filesystem
MINIMUM_IO_SIZE=512
PHYSICAL_SECTOR_SIZE=512
LOGICAL_SECTOR_SIZE=512
PART_ENTRY_SCHEME=dos
PART_ENTRY_TYPE=0x83
PART_ENTRY_FLAGS=0x80
PART_ENTRY_NUMBER=1
PART_ENTRY_OFFSET=2048
PART_ENTRY_SIZE=2097152
PART_ENTRY_DISK=8:0

View File

@@ -0,0 +1 @@
[{"id_fs_uuid": "3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM", "id_fs_uuid_enc": "3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM", "id_fs_version": "LVM2\\x20001", "id_fs_type": "LVM2_member", "id_fs_usage": "raid", "id_iolimit_minimum_io_size": 512, "id_iolimit_physical_sector_size": 512, "id_iolimit_logical_sector_size": 512, "id_part_entry_scheme": "dos", "id_part_entry_type": "0x8e", "id_part_entry_number": 2, "id_part_entry_offset": 2099200, "id_part_entry_size": 39843840, "id_part_entry_disk": "8:0"}, {"id_fs_uuid": "05d927bb-5875-49e3-ada1-7f46cb31c932", "id_fs_uuid_enc": "05d927bb-5875-49e3-ada1-7f46cb31c932", "id_fs_type": "xfs", "id_fs_usage": "filesystem", "id_iolimit_minimum_io_size": 512, "id_iolimit_physical_sector_size": 512, "id_iolimit_logical_sector_size": 512, "id_part_entry_scheme": "dos", "id_part_entry_type": "0x83", "id_part_entry_flags": "0x80", "id_part_entry_number": 1, "id_part_entry_offset": 2048, "id_part_entry_size": 2097152, "id_part_entry_disk": "8:0"}]

View File

@@ -0,0 +1,29 @@
ID_FS_UUID=3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM
ID_FS_UUID_ENC=3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM
ID_FS_VERSION=LVM2\x20001
ID_FS_TYPE=LVM2_member
ID_FS_USAGE=raid
ID_IOLIMIT_MINIMUM_IO_SIZE=512
ID_IOLIMIT_PHYSICAL_SECTOR_SIZE=512
ID_IOLIMIT_LOGICAL_SECTOR_SIZE=512
ID_PART_ENTRY_SCHEME=dos
ID_PART_ENTRY_TYPE=0x8e
ID_PART_ENTRY_NUMBER=2
ID_PART_ENTRY_OFFSET=2099200
ID_PART_ENTRY_SIZE=39843840
ID_PART_ENTRY_DISK=8:0
ID_FS_UUID=05d927bb-5875-49e3-ada1-7f46cb31c932
ID_FS_UUID_ENC=05d927bb-5875-49e3-ada1-7f46cb31c932
ID_FS_TYPE=xfs
ID_FS_USAGE=filesystem
ID_IOLIMIT_MINIMUM_IO_SIZE=512
ID_IOLIMIT_PHYSICAL_SECTOR_SIZE=512
ID_IOLIMIT_LOGICAL_SECTOR_SIZE=512
ID_PART_ENTRY_SCHEME=dos
ID_PART_ENTRY_TYPE=0x83
ID_PART_ENTRY_FLAGS=0x80
ID_PART_ENTRY_NUMBER=1
ID_PART_ENTRY_OFFSET=2048
ID_PART_ENTRY_SIZE=2097152
ID_PART_ENTRY_DISK=8:0

View File

@@ -0,0 +1 @@
[{"id_fs_uuid": "05d927bb-5875-49e3-ada1-7f46cb31c932", "id_fs_uuid_enc": "05d927bb-5875-49e3-ada1-7f46cb31c932", "id_fs_type": "xfs", "id_fs_usage": "filesystem", "id_iolimit_minimum_io_size": 512, "id_iolimit_physical_sector_size": 512, "id_iolimit_logical_sector_size": 512, "id_part_entry_scheme": "dos", "id_part_entry_type": "0x83", "id_part_entry_flags": "0x80", "id_part_entry_number": 1, "id_part_entry_offset": 2048, "id_part_entry_size": 2097152, "id_part_entry_disk": "8:0"}]

View File

@@ -0,0 +1,14 @@
ID_FS_UUID=05d927bb-5875-49e3-ada1-7f46cb31c932
ID_FS_UUID_ENC=05d927bb-5875-49e3-ada1-7f46cb31c932
ID_FS_TYPE=xfs
ID_FS_USAGE=filesystem
ID_IOLIMIT_MINIMUM_IO_SIZE=512
ID_IOLIMIT_PHYSICAL_SECTOR_SIZE=512
ID_IOLIMIT_LOGICAL_SECTOR_SIZE=512
ID_PART_ENTRY_SCHEME=dos
ID_PART_ENTRY_TYPE=0x83
ID_PART_ENTRY_FLAGS=0x80
ID_PART_ENTRY_NUMBER=1
ID_PART_ENTRY_OFFSET=2048
ID_PART_ENTRY_SIZE=2097152
ID_PART_ENTRY_DISK=8:0

View File

@@ -0,0 +1 @@
[{"device": "/dev/sda2", "uuid": "3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM", "type": "LVM2_member"}]

View File

@@ -0,0 +1 @@
/dev/sda2: UUID="3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM" TYPE="LVM2_member"

1
tests/fixtures/centos-7.7/blkid.json vendored Normal file
View File

@@ -0,0 +1 @@
[{"device": "/dev/sda1", "uuid": "05d927bb-5875-49e3-ada1-7f46cb31c932", "type": "xfs"}, {"device": "/dev/sda2", "uuid": "3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM", "type": "LVM2_member"}, {"device": "/dev/mapper/centos-root", "uuid": "07d718ef-950c-4e5b-98e0-42a1147b77d9", "type": "xfs"}, {"device": "/dev/mapper/centos-swap", "uuid": "615eb89d-bcbf-46ad-80e3-c483ef5c931f", "type": "swap"}]

4
tests/fixtures/centos-7.7/blkid.out vendored Normal file
View File

@@ -0,0 +1,4 @@
/dev/sda1: UUID="05d927bb-5875-49e3-ada1-7f46cb31c932" TYPE="xfs"
/dev/sda2: UUID="3klkIj-w1qk-DkJi-0XBJ-y3o7-i2Ac-vHqWBM" TYPE="LVM2_member"
/dev/mapper/centos-root: UUID="07d718ef-950c-4e5b-98e0-42a1147b77d9" TYPE="xfs"
/dev/mapper/centos-swap: UUID="615eb89d-bcbf-46ad-80e3-c483ef5c931f" TYPE="swap"

File diff suppressed because one or more lines are too long

60
tests/fixtures/centos-7.7/dig-axfr.out vendored Normal file
View File

@@ -0,0 +1,60 @@
; <<>> DiG 9.11.4-P2-RedHat-9.11.4-9.P2.el7 <<>> @81.4.108.41 AXFR zonetransfer.me +nocookie
; (1 server found)
;; global options: +cmd
zonetransfer.me. 7200 IN SOA nsztm1.digi.ninja. robin.digi.ninja. 2019100801 172800 900 1209600 3600
zonetransfer.me. 300 IN HINFO "Casio fx-700G" "Windows XP"
zonetransfer.me. 301 IN TXT "google-site-verification=tyP28J7JAUHA9fw2sHXMgcCC0I6XBmmoVi04VlMewxA"
zonetransfer.me. 7200 IN MX 0 ASPMX.L.GOOGLE.COM.
zonetransfer.me. 7200 IN MX 10 ALT1.ASPMX.L.GOOGLE.COM.
zonetransfer.me. 7200 IN MX 10 ALT2.ASPMX.L.GOOGLE.COM.
zonetransfer.me. 7200 IN MX 20 ASPMX2.GOOGLEMAIL.COM.
zonetransfer.me. 7200 IN MX 20 ASPMX3.GOOGLEMAIL.COM.
zonetransfer.me. 7200 IN MX 20 ASPMX4.GOOGLEMAIL.COM.
zonetransfer.me. 7200 IN MX 20 ASPMX5.GOOGLEMAIL.COM.
zonetransfer.me. 7200 IN A 5.196.105.14
zonetransfer.me. 7200 IN NS nsztm1.digi.ninja.
zonetransfer.me. 7200 IN NS nsztm2.digi.ninja.
_acme-challenge.zonetransfer.me. 301 IN TXT "6Oa05hbUJ9xSsvYy7pApQvwCUSSGgxvrbdizjePEsZI"
_sip._tcp.zonetransfer.me. 14000 IN SRV 0 0 5060 www.zonetransfer.me.
14.105.196.5.IN-ADDR.ARPA.zonetransfer.me. 7200 IN PTR www.zonetransfer.me.
asfdbauthdns.zonetransfer.me. 7900 IN AFSDB 1 asfdbbox.zonetransfer.me.
asfdbbox.zonetransfer.me. 7200 IN A 127.0.0.1
asfdbvolume.zonetransfer.me. 7800 IN AFSDB 1 asfdbbox.zonetransfer.me.
canberra-office.zonetransfer.me. 7200 IN A 202.14.81.230
cmdexec.zonetransfer.me. 300 IN TXT "; ls"
contact.zonetransfer.me. 2592000 IN TXT "Remember to call or email Pippa on +44 123 4567890 or pippa@zonetransfer.me when making DNS changes"
dc-office.zonetransfer.me. 7200 IN A 143.228.181.132
deadbeef.zonetransfer.me. 7201 IN AAAA dead:beaf::
dr.zonetransfer.me. 300 IN LOC 53 20 56.558 N 1 38 33.526 W 0.00m 1m 10000m 10m
DZC.zonetransfer.me. 7200 IN TXT "AbCdEfG"
email.zonetransfer.me. 2222 IN NAPTR 1 1 "P" "E2U+email" "" email.zonetransfer.me.zonetransfer.me.
email.zonetransfer.me. 7200 IN A 74.125.206.26
Hello.zonetransfer.me. 7200 IN TXT "Hi to Josh and all his class"
home.zonetransfer.me. 7200 IN A 127.0.0.1
Info.zonetransfer.me. 7200 IN TXT "ZoneTransfer.me service provided by Robin Wood - robin@digi.ninja. See http://digi.ninja/projects/zonetransferme.php for more information."
internal.zonetransfer.me. 300 IN NS intns1.zonetransfer.me.
internal.zonetransfer.me. 300 IN NS intns2.zonetransfer.me.
intns1.zonetransfer.me. 300 IN A 81.4.108.41
intns2.zonetransfer.me. 300 IN A 167.88.42.94
office.zonetransfer.me. 7200 IN A 4.23.39.254
ipv6actnow.org.zonetransfer.me. 7200 IN AAAA 2001:67c:2e8:11::c100:1332
owa.zonetransfer.me. 7200 IN A 207.46.197.32
robinwood.zonetransfer.me. 302 IN TXT "Robin Wood"
rp.zonetransfer.me. 321 IN RP robin.zonetransfer.me. robinwood.zonetransfer.me.
sip.zonetransfer.me. 3333 IN NAPTR 2 3 "P" "E2U+sip" "!^.*$!sip:customer-service@zonetransfer.me!" .
sqli.zonetransfer.me. 300 IN TXT "' or 1=1 --"
sshock.zonetransfer.me. 7200 IN TXT "() { :]}; echo ShellShocked"
staging.zonetransfer.me. 7200 IN CNAME www.sydneyoperahouse.com.
alltcpportsopen.firewall.test.zonetransfer.me. 301 IN A 127.0.0.1
testing.zonetransfer.me. 301 IN CNAME www.zonetransfer.me.
vpn.zonetransfer.me. 4000 IN A 174.36.59.154
www.zonetransfer.me. 7200 IN A 5.196.105.14
xss.zonetransfer.me. 300 IN TXT "'><script>alert('Boo')</script>"
zonetransfer.me. 7200 IN SOA nsztm1.digi.ninja. robin.digi.ninja. 2019100801 172800 900 1209600 3600
;; Query time: 182 msec
;; SERVER: 81.4.108.41#53(81.4.108.41)
;; WHEN: Wed Mar 25 20:01:47 PDT 2020
;; XFR size: 50 records (messages 1, bytes 1994)

1
tests/fixtures/centos-7.7/file.json vendored Normal file
View File

@@ -0,0 +1 @@
[{"filename": "bin", "type": "directory"}, {"filename": "digout", "type": "ASCII text"}, {"filename": "file with spaces in the name", "type": "empty"}, {"filename": "git", "type": "directory"}, {"filename": "id-centos.out", "type": "ASCII text"}, {"filename": "ifcfg.json", "type": "ASCII text, with very long lines"}, {"filename": "ifconfig.out", "type": "ASCII text"}, {"filename": "iptables-tests", "type": "directory"}, {"filename": "journaljson", "type": "ASCII text, with very long lines"}, {"filename": "jp", "type": "ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped"}, {"filename": "jp_1.1.12_linux_x86_64.zip", "type": "Zip archive data, at least v2.0 to extract"}, {"filename": "lastb.out", "type": "ASCII text"}, {"filename": "lsblk-cols", "type": "UTF-8 Unicode text"}, {"filename": "psfile.txt", "type": "ASCII text, with very long lines"}, {"filename": "resizeterm.sh", "type": "Bourne-Again shell script, ASCII text executable"}, {"filename": "routeout", "type": "ASCII text"}, {"filename": "ss-aeep.out", "type": "ASCII text"}, {"filename": "ssout", "type": "ASCII text"}, {"filename": "systemctl.out", "type": "UTF-8 Unicode text"}, {"filename": "testfiles", "type": "directory"}, {"filename": "tmp", "type": "directory"}, {"filename": "top.out", "type": "ASCII text, with escape sequences"}, {"filename": "who-aH.out", "type": "ASCII text"}, {"filename": "who.out", "type": "ASCII text"}, {"filename": "whotext", "type": "ASCII text"}]

25
tests/fixtures/centos-7.7/file.out vendored Normal file
View File

@@ -0,0 +1,25 @@
bin: directory
digout: ASCII text
file with spaces in the name: empty
git: directory
id-centos.out: ASCII text
ifcfg.json: ASCII text, with very long lines
ifconfig.out: ASCII text
iptables-tests: directory
journaljson: ASCII text, with very long lines
jp: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
jp_1.1.12_linux_x86_64.zip: Zip archive data, at least v2.0 to extract
lastb.out: ASCII text
lsblk-cols: UTF-8 Unicode text
psfile.txt: ASCII text, with very long lines
resizeterm.sh: Bourne-Again shell script, ASCII text executable
routeout: ASCII text
ss-aeep.out: ASCII text
ssout: ASCII text
systemctl.out: UTF-8 Unicode text
testfiles: directory
tmp: directory
top.out: ASCII text, with escape sequences
who-aH.out: ASCII text
who.out: ASCII text
whotext: ASCII text

1
tests/fixtures/centos-7.7/group.json vendored Normal file
View File

@@ -0,0 +1 @@
[{"group_name": "root", "password": "x", "gid": 0, "members": []}, {"group_name": "bin", "password": "x", "gid": 1, "members": []}, {"group_name": "daemon", "password": "x", "gid": 2, "members": []}, {"group_name": "sys", "password": "x", "gid": 3, "members": []}, {"group_name": "adm", "password": "x", "gid": 4, "members": []}, {"group_name": "tty", "password": "x", "gid": 5, "members": []}, {"group_name": "disk", "password": "x", "gid": 6, "members": []}, {"group_name": "lp", "password": "x", "gid": 7, "members": []}, {"group_name": "mem", "password": "x", "gid": 8, "members": []}, {"group_name": "kmem", "password": "x", "gid": 9, "members": []}, {"group_name": "wheel", "password": "x", "gid": 10, "members": ["joeuser"]}, {"group_name": "cdrom", "password": "x", "gid": 11, "members": []}, {"group_name": "mail", "password": "x", "gid": 12, "members": ["postfix"]}, {"group_name": "man", "password": "x", "gid": 15, "members": []}, {"group_name": "dialout", "password": "x", "gid": 18, "members": []}, {"group_name": "floppy", "password": "x", "gid": 19, "members": []}, {"group_name": "games", "password": "x", "gid": 20, "members": []}, {"group_name": "tape", "password": "x", "gid": 33, "members": []}, {"group_name": "video", "password": "x", "gid": 39, "members": []}, {"group_name": "ftp", "password": "x", "gid": 50, "members": []}, {"group_name": "lock", "password": "x", "gid": 54, "members": []}, {"group_name": "audio", "password": "x", "gid": 63, "members": []}, {"group_name": "nobody", "password": "x", "gid": 99, "members": []}, {"group_name": "users", "password": "x", "gid": 100, "members": []}, {"group_name": "utmp", "password": "x", "gid": 22, "members": []}, {"group_name": "utempter", "password": "x", "gid": 35, "members": []}, {"group_name": "input", "password": "x", "gid": 999, "members": []}, {"group_name": "systemd-journal", "password": "x", "gid": 190, "members": []}, {"group_name": "systemd-network", "password": "x", "gid": 192, "members": []}, {"group_name": "dbus", "password": "x", "gid": 81, "members": []}, {"group_name": "polkitd", "password": "x", "gid": 998, "members": []}, {"group_name": "ssh_keys", "password": "x", "gid": 997, "members": []}, {"group_name": "sshd", "password": "x", "gid": 74, "members": []}, {"group_name": "postdrop", "password": "x", "gid": 90, "members": []}, {"group_name": "postfix", "password": "x", "gid": 89, "members": []}, {"group_name": "chrony", "password": "x", "gid": 996, "members": []}, {"group_name": "joeuser", "password": "x", "gid": 1000, "members": ["joeuser"]}, {"group_name": "cgred", "password": "x", "gid": 995, "members": []}, {"group_name": "dockerroot", "password": "x", "gid": 994, "members": []}]

39
tests/fixtures/centos-7.7/group.out vendored Normal file
View File

@@ -0,0 +1,39 @@
root:x:0:
bin:x:1:
daemon:x:2:
sys:x:3:
adm:x:4:
tty:x:5:
disk:x:6:
lp:x:7:
mem:x:8:
kmem:x:9:
wheel:x:10:joeuser
cdrom:x:11:
mail:x:12:postfix
man:x:15:
dialout:x:18:
floppy:x:19:
games:x:20:
tape:x:33:
video:x:39:
ftp:x:50:
lock:x:54:
audio:x:63:
nobody:x:99:
users:x:100:
utmp:x:22:
utempter:x:35:
input:x:999:
systemd-journal:x:190:
systemd-network:x:192:
dbus:x:81:
polkitd:x:998:
ssh_keys:x:997:
sshd:x:74:
postdrop:x:90:
postfix:x:89:
chrony:x:996:
joeuser:x:1000:joeuser
cgred:x:995:
dockerroot:x:994:

View File

@@ -0,0 +1 @@
[{"group_name": "root", "password": "", "administrators": [], "members": []}, {"group_name": "bin", "password": "", "administrators": [], "members": []}, {"group_name": "daemon", "password": "", "administrators": [], "members": []}, {"group_name": "sys", "password": "", "administrators": [], "members": []}, {"group_name": "adm", "password": "", "administrators": [], "members": []}, {"group_name": "tty", "password": "", "administrators": [], "members": []}, {"group_name": "disk", "password": "", "administrators": [], "members": []}, {"group_name": "lp", "password": "", "administrators": [], "members": []}, {"group_name": "mem", "password": "", "administrators": [], "members": []}, {"group_name": "kmem", "password": "", "administrators": [], "members": []}, {"group_name": "wheel", "password": "", "administrators": [], "members": ["joeuser"]}, {"group_name": "cdrom", "password": "", "administrators": [], "members": []}, {"group_name": "mail", "password": "", "administrators": [], "members": ["postfix"]}, {"group_name": "man", "password": "", "administrators": [], "members": []}, {"group_name": "dialout", "password": "", "administrators": [], "members": []}, {"group_name": "floppy", "password": "", "administrators": [], "members": []}, {"group_name": "games", "password": "", "administrators": [], "members": []}, {"group_name": "tape", "password": "", "administrators": [], "members": []}, {"group_name": "video", "password": "", "administrators": [], "members": []}, {"group_name": "ftp", "password": "", "administrators": [], "members": []}, {"group_name": "lock", "password": "", "administrators": [], "members": []}, {"group_name": "audio", "password": "", "administrators": [], "members": []}, {"group_name": "nobody", "password": "", "administrators": [], "members": []}, {"group_name": "users", "password": "", "administrators": [], "members": []}, {"group_name": "utmp", "password": "!", "administrators": [], "members": []}, {"group_name": "utempter", "password": "!", "administrators": [], "members": []}, {"group_name": "input", "password": "!", "administrators": [], "members": []}, {"group_name": "systemd-journal", "password": "!", "administrators": [], "members": []}, {"group_name": "systemd-network", "password": "!", "administrators": [], "members": []}, {"group_name": "dbus", "password": "!", "administrators": [], "members": []}, {"group_name": "polkitd", "password": "!", "administrators": [], "members": []}, {"group_name": "ssh_keys", "password": "!", "administrators": [], "members": []}, {"group_name": "sshd", "password": "!", "administrators": [], "members": []}, {"group_name": "postdrop", "password": "!", "administrators": [], "members": []}, {"group_name": "postfix", "password": "!", "administrators": [], "members": []}, {"group_name": "chrony", "password": "!", "administrators": [], "members": []}, {"group_name": "joeuser", "password": "!!", "administrators": [], "members": ["joeuser"]}, {"group_name": "cgred", "password": "!", "administrators": [], "members": []}, {"group_name": "dockerroot", "password": "!", "administrators": [], "members": []}]

39
tests/fixtures/centos-7.7/gshadow.out vendored Normal file
View File

@@ -0,0 +1,39 @@
root:::
bin:::
daemon:::
sys:::
adm:::
tty:::
disk:::
lp:::
mem:::
kmem:::
wheel:::joeuser
cdrom:::
mail:::postfix
man:::
dialout:::
floppy:::
games:::
tape:::
video:::
ftp:::
lock:::
audio:::
nobody:::
users:::
utmp:!::
utempter:!::
input:!::
systemd-journal:!::
systemd-network:!::
dbus:!::
polkitd:!::
ssh_keys:!::
sshd:!::
postdrop:!::
postfix:!::
chrony:!::
joeuser:!!::joeuser
cgred:!::
dockerroot:!::

1
tests/fixtures/centos-7.7/last-w.json vendored Normal file

File diff suppressed because one or more lines are too long

69
tests/fixtures/centos-7.7/last-w.out vendored Normal file
View File

@@ -0,0 +1,69 @@
kbrazil ttyS0 Fri Feb 28 13:49 still logged in
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Fri Feb 28 12:56 - 14:54 (01:58)
kbrazil ttyS0 Thu Feb 27 16:01 - crash (20:54)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Thu Feb 27 15:51 - 14:54 (23:02)
kbrazil ttyS0 Thu Feb 27 10:50 - crash (05:01)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Wed Feb 26 20:05 - 14:54 (1+18:49)
kbrazil ttyS0 Thu Feb 20 14:42 - crash (6+05:23)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Thu Feb 20 14:41 - 14:54 (8+00:12)
kbrazil ttyS0 Mon Feb 17 17:48 - crash (2+20:52)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Mon Feb 17 17:48 - 14:54 (10+21:06)
kbrazil ttyS0 Thu Feb 13 16:44 - crash (4+01:03)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Thu Feb 13 16:44 - 14:54 (14+22:10)
kbrazil ttyS0 Wed Feb 5 14:23 - crash (8+02:20)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Wed Feb 5 11:43 - 14:54 (23+03:11)
kbrazil ttyS0 Tue Feb 4 14:28 - crash (21:15)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Tue Feb 4 01:28 - 14:54 (24+13:26)
kbrazil ttyS0 Mon Jan 13 17:28 - crash (21+07:59)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Mon Jan 13 16:16 - 14:54 (45+22:38)
kbrazil ttyS0 Mon Dec 16 11:15 - crash (28+05:01)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Mon Dec 16 11:14 - 14:54 (74+03:40)
kbrazil ttyS0 Wed Dec 4 21:41 - crash (11+13:33)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Wed Dec 4 21:40 - 14:54 (85+17:13)
kbrazil pts/1 Sat Nov 16 14:40 - 14:40 (00:00)
kbrazil pts/1 Sat Nov 16 14:39 - 14:39 (00:00)
kbrazil pts/0 localhost Tue Nov 12 07:19 - crash (22+14:21)
kbrazil ttyS0 Tue Nov 12 07:18 - crash (22+14:22)
kbrazil pts/0 localhost Sun Nov 10 08:21 - 15:22 (1+07:01)
kbrazil ttyS0 Sat Nov 9 10:34 - 07:16 (2+20:42)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Sat Nov 9 10:34 - 14:54 (111+04:20)
kbrazil tty1 Fri Nov 8 07:49 - crash (1+02:45)
kbrazil pts/0 192.168.71.1 Fri Nov 8 06:29 - crash (1+04:04)
kbrazil ttyS0 Fri Nov 8 06:24 - crash (1+04:09)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Fri Nov 8 06:14 - 14:54 (112+08:40)
kbrazil tty1 Sun Nov 3 12:20 - crash (4+17:54)
kbrazil ttyS0 Sun Nov 3 11:04 - 11:05 (00:01)
kbrazil pts/0 192.168.71.1 Sat Nov 2 19:26 - crash (5+11:47)
kbrazil ttyS0 Fri Nov 1 15:14 - 11:03 (1+20:49)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Fri Nov 1 15:13 - 14:54 (119+00:41)
kbrazil ttyS0 Fri Nov 1 11:16 - 11:36 (00:20)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Fri Nov 1 06:00 - 11:36 (05:36)
kbrazil ttyS0 Tue Oct 29 18:17 - crash (2+11:43)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Tue Oct 29 18:16 - 11:36 (2+17:19)
kbrazil pts/0 192.168.71.1 Sat Oct 26 09:53 - 15:13 (05:19)
kbrazil ttyS0 Fri Oct 25 18:22 - crash (3+23:54)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Fri Oct 25 18:21 - 11:36 (6+17:14)
kbrazil ttyS0 Fri Oct 25 17:14 - 18:21 (01:06)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Fri Oct 25 17:13 - 11:36 (6+18:22)
kbrazil ttyS0 Fri Oct 25 15:43 - 17:13 (01:29)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Fri Oct 25 13:29 - 17:13 (03:44)
kbrazil ttyS0 Mon Oct 21 13:19 - 19:22 (2+06:03)
reboot system boot 3.10.0-1062.1.2.el7.x86_64 Mon Oct 21 13:17 - 19:22 (2+06:05)
kbrazil ttyS0 Wed Oct 16 03:23 - crash (5+09:54)
kbrazil ttyS0 Tue Oct 15 16:49 - 03:23 (10:34)
kbrazil ttyS0 Tue Oct 15 10:39 - 16:48 (06:09)
reboot system boot 3.10.0-957.27.2.el7.x86_64 Tue Oct 15 10:39 - 19:22 (8+08:43)
kbrazil ttyS0 Thu Aug 15 16:05 - 16:05 (00:00)
reboot system boot 3.10.0-957.27.2.el7.x86_64 Thu Aug 15 16:05 - 16:05 (00:00)
reboot system boot 3.10.0-957.27.2.el7.x86_64 Thu Aug 15 16:00 - 16:05 (00:05)
kbrazil ttyS0 Thu Aug 15 14:25 - crash (01:35)
reboot system boot 3.10.0-957.27.2.el7.x86_64 Thu Aug 15 14:24 - 16:05 (01:41)
kbrazil ttyS0 Thu Aug 15 11:58 - crash (02:25)
reboot system boot 3.10.0-957.el7.x86_64 Thu Aug 15 11:58 - 16:05 (04:07)
kbrazil ttyS0 Thu Aug 15 11:57 - 11:57 (00:00)
reboot system boot 3.10.0-957.el7.x86_64 Thu Aug 15 11:57 - 16:05 (04:08)
kbrazil pts/0 192.168.71.1 Thu Aug 15 10:58 - 11:56 (00:58)
root tty1 Thu Aug 15 10:57 - 11:56 (00:59)
reboot system boot 3.10.0-957.el7.x86_64 Thu Aug 15 10:57 - 11:56 (00:59)
wtmp begins Thu Aug 15 10:57:06 2019

1
tests/fixtures/centos-7.7/last.json vendored Normal file

File diff suppressed because one or more lines are too long

69
tests/fixtures/centos-7.7/last.out vendored Normal file
View File

@@ -0,0 +1,69 @@
kbrazil ttyS0 Fri Feb 28 13:49 still logged in
reboot system boot 3.10.0-1062.1.2. Fri Feb 28 12:56 - 14:52 (01:56)
kbrazil ttyS0 Thu Feb 27 16:01 - crash (20:54)
reboot system boot 3.10.0-1062.1.2. Thu Feb 27 15:51 - 14:52 (23:01)
kbrazil ttyS0 Thu Feb 27 10:50 - crash (05:01)
reboot system boot 3.10.0-1062.1.2. Wed Feb 26 20:05 - 14:52 (1+18:47)
kbrazil ttyS0 Thu Feb 20 14:42 - crash (6+05:23)
reboot system boot 3.10.0-1062.1.2. Thu Feb 20 14:41 - 14:52 (8+00:11)
kbrazil ttyS0 Mon Feb 17 17:48 - crash (2+20:52)
reboot system boot 3.10.0-1062.1.2. Mon Feb 17 17:48 - 14:52 (10+21:04)
kbrazil ttyS0 Thu Feb 13 16:44 - crash (4+01:03)
reboot system boot 3.10.0-1062.1.2. Thu Feb 13 16:44 - 14:52 (14+22:08)
kbrazil ttyS0 Wed Feb 5 14:23 - crash (8+02:20)
reboot system boot 3.10.0-1062.1.2. Wed Feb 5 11:43 - 14:52 (23+03:09)
kbrazil ttyS0 Tue Feb 4 14:28 - crash (21:15)
reboot system boot 3.10.0-1062.1.2. Tue Feb 4 01:28 - 14:52 (24+13:24)
kbrazil ttyS0 Mon Jan 13 17:28 - crash (21+07:59)
reboot system boot 3.10.0-1062.1.2. Mon Jan 13 16:16 - 14:52 (45+22:36)
kbrazil ttyS0 Mon Dec 16 11:15 - crash (28+05:01)
reboot system boot 3.10.0-1062.1.2. Mon Dec 16 11:14 - 14:52 (74+03:38)
kbrazil ttyS0 Wed Dec 4 21:41 - crash (11+13:33)
reboot system boot 3.10.0-1062.1.2. Wed Dec 4 21:40 - 14:52 (85+17:12)
kbrazil pts/1 Sat Nov 16 14:40 - 14:40 (00:00)
kbrazil pts/1 Sat Nov 16 14:39 - 14:39 (00:00)
kbrazil pts/0 localhost Tue Nov 12 07:19 - crash (22+14:21)
kbrazil ttyS0 Tue Nov 12 07:18 - crash (22+14:22)
kbrazil pts/0 localhost Sun Nov 10 08:21 - 15:22 (1+07:01)
kbrazil ttyS0 Sat Nov 9 10:34 - 07:16 (2+20:42)
reboot system boot 3.10.0-1062.1.2. Sat Nov 9 10:34 - 14:52 (111+04:18)
kbrazil tty1 Fri Nov 8 07:49 - crash (1+02:45)
kbrazil pts/0 192.168.71.1 Fri Nov 8 06:29 - crash (1+04:04)
kbrazil ttyS0 Fri Nov 8 06:24 - crash (1+04:09)
reboot system boot 3.10.0-1062.1.2. Fri Nov 8 06:14 - 14:52 (112+08:38)
kbrazil tty1 Sun Nov 3 12:20 - crash (4+17:54)
kbrazil ttyS0 Sun Nov 3 11:04 - 11:05 (00:01)
kbrazil pts/0 192.168.71.1 Sat Nov 2 19:26 - crash (5+11:47)
kbrazil ttyS0 Fri Nov 1 15:14 - 11:03 (1+20:49)
reboot system boot 3.10.0-1062.1.2. Fri Nov 1 15:13 - 14:52 (119+00:39)
kbrazil ttyS0 Fri Nov 1 11:16 - 11:36 (00:20)
reboot system boot 3.10.0-1062.1.2. Fri Nov 1 06:00 - 11:36 (05:36)
kbrazil ttyS0 Tue Oct 29 18:17 - crash (2+11:43)
reboot system boot 3.10.0-1062.1.2. Tue Oct 29 18:16 - 11:36 (2+17:19)
kbrazil pts/0 192.168.71.1 Sat Oct 26 09:53 - 15:13 (05:19)
kbrazil ttyS0 Fri Oct 25 18:22 - crash (3+23:54)
reboot system boot 3.10.0-1062.1.2. Fri Oct 25 18:21 - 11:36 (6+17:14)
kbrazil ttyS0 Fri Oct 25 17:14 - 18:21 (01:06)
reboot system boot 3.10.0-1062.1.2. Fri Oct 25 17:13 - 11:36 (6+18:22)
kbrazil ttyS0 Fri Oct 25 15:43 - 17:13 (01:29)
reboot system boot 3.10.0-1062.1.2. Fri Oct 25 13:29 - 17:13 (03:44)
kbrazil ttyS0 Mon Oct 21 13:19 - 19:22 (2+06:03)
reboot system boot 3.10.0-1062.1.2. Mon Oct 21 13:17 - 19:22 (2+06:05)
kbrazil ttyS0 Wed Oct 16 03:23 - crash (5+09:54)
kbrazil ttyS0 Tue Oct 15 16:49 - 03:23 (10:34)
kbrazil ttyS0 Tue Oct 15 10:39 - 16:48 (06:09)
reboot system boot 3.10.0-957.27.2. Tue Oct 15 10:39 - 19:22 (8+08:43)
kbrazil ttyS0 Thu Aug 15 16:05 - 16:05 (00:00)
reboot system boot 3.10.0-957.27.2. Thu Aug 15 16:05 - 16:05 (00:00)
reboot system boot 3.10.0-957.27.2. Thu Aug 15 16:00 - 16:05 (00:05)
kbrazil ttyS0 Thu Aug 15 14:25 - crash (01:35)
reboot system boot 3.10.0-957.27.2. Thu Aug 15 14:24 - 16:05 (01:41)
kbrazil ttyS0 Thu Aug 15 11:58 - crash (02:25)
reboot system boot 3.10.0-957.el7.x Thu Aug 15 11:58 - 16:05 (04:07)
kbrazil ttyS0 Thu Aug 15 11:57 - 11:57 (00:00)
reboot system boot 3.10.0-957.el7.x Thu Aug 15 11:57 - 16:05 (04:08)
kbrazil pts/0 192.168.71.1 Thu Aug 15 10:58 - 11:56 (00:58)
root tty1 Thu Aug 15 10:57 - 11:56 (00:59)
reboot system boot 3.10.0-957.el7.x Thu Aug 15 10:57 - 11:56 (00:59)
wtmp begins Thu Aug 15 10:57:06 2019

1
tests/fixtures/centos-7.7/lastb.json vendored Normal file
View File

@@ -0,0 +1 @@
[{"user": "kbrazil", "tty": "ttyS0", "hostname": null, "login": "Fri Feb 28 13:49", "logout": "13:49", "duration": "00:00"}, {"user": "kbrazil", "tty": "ssh:notty", "hostname": "192.168.71.1", "login": "Thu Feb 27 10:13", "logout": "10:13", "duration": "00:00"}, {"user": "kbrazil", "tty": "ttyS0", "hostname": null, "login": "Thu Feb 20 14:41", "logout": "14:41", "duration": "00:00"}, {"user": "kbrazil", "tty": "ttyS0", "hostname": null, "login": "Mon Feb 17 17:48", "logout": "17:48", "duration": "00:00"}]

6
tests/fixtures/centos-7.7/lastb.out vendored Normal file
View File

@@ -0,0 +1,6 @@
kbrazil ttyS0 Fri Feb 28 13:49 - 13:49 (00:00)
kbrazil ssh:notty 192.168.71.1 Thu Feb 27 10:13 - 10:13 (00:00)
kbrazil ttyS0 Thu Feb 20 14:41 - 14:41 (00:00)
kbrazil ttyS0 Mon Feb 17 17:48 - 17:48 (00:00)
btmp begins Mon Feb 17 17:48:53 2020

View File

@@ -0,0 +1 @@
[{"filename": "systemd-private-016de60725a3426792b93fc9f120b8f0-chronyd.service-oZqq4u", "parent": "."}, {"filename": "systemd-private-a30a5a178daa4042b42dfaf5ff9e5f68-chronyd.service-a1tpxv", "parent": "."}, {"filename": "systemd-private-af69d7360f3e40cfa947358c0fb5a6f8-chronyd.service-T3MQ4j", "parent": "."}, {"filename": "tmp.CvALl2jE6u", "parent": "."}, {"filename": "tmp.e7AlxSxY5a", "parent": "."}, {"filename": "tmp.uXm9yegjwj", "parent": "."}, {"filename": "a regular filename", "parent": "./lstest"}, {"filename": "this file has", "parent": "./lstest"}, {"filename": "a combination", "parent": "./lstest"}, {"filename": "of everything", "parent": "./lstest"}, {"filename": "this file has", "parent": "./lstest"}, {"filename": "a newline inside", "parent": "./lstest"}, {"filename": "this file has", "parent": "./lstest"}, {"filename": "four contiguous newlines inside", "parent": "./lstest"}, {"filename": "this file", "parent": "./lstest"}, {"filename": "has", "parent": "./lstest"}, {"filename": "six", "parent": "./lstest"}, {"filename": "newlines", "parent": "./lstest"}, {"filename": "within", "parent": "./lstest"}, {"filename": "this file starts with four newlines", "parent": "./lstest"}, {"filename": "this file starts with one newline", "parent": "./lstest"}]

View File

@@ -0,0 +1,43 @@
.:
lstest
systemd-private-016de60725a3426792b93fc9f120b8f0-chronyd.service-oZqq4u
systemd-private-a30a5a178daa4042b42dfaf5ff9e5f68-chronyd.service-a1tpxv
systemd-private-af69d7360f3e40cfa947358c0fb5a6f8-chronyd.service-T3MQ4j
tmp.CvALl2jE6u
tmp.e7AlxSxY5a
tmp.uXm9yegjwj
./lstest:
a regular filename
this file has
a combination
of everything
this file has
a newline inside
this file has
four contiguous newlines inside
this file
has
six
newlines
within
this file starts with four newlines
this file starts with one newline

View File

@@ -0,0 +1 @@
[{"filename": "a regular filename", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:12"}, {"filename": "\n\nthis file has\na combination\n\n\nof everything\n\n\n\n", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:17"}, {"filename": "this file has\na newline inside", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:14"}, {"filename": "this file has\n\n\n\nfour contiguous newlines inside", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:14"}, {"filename": "this file\nhas\nsix\n\nnewlines\n\nwithin", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:16"}, {"filename": "\n\n\n\nthis file starts with four newlines", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:40"}, {"filename": "\nthis file starts with one newline", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:13"}]

View File

@@ -0,0 +1,34 @@
total 0
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:12 a regular filename
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:17
this file has
a combination
of everything
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:14 this file has
a newline inside
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:14 this file has
four contiguous newlines inside
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:16 this file
has
six
newlines
within
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:40
this file starts with four newlines
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:13
this file starts with one newline

View File

@@ -0,0 +1 @@
[{"filename": "lstest", "parent": ".", "flags": "drwxrwxr-x.", "links": 2, "owner": "kbrazil", "group": "kbrazil", "size": 4096, "date": "Feb 22 00:40"}, {"filename": "systemd-private-016de60725a3426792b93fc9f120b8f0-chronyd.service-oZqq4u", "parent": ".", "flags": "drwx------.", "links": 3, "owner": "root", "group": "root", "size": 17, "date": "Feb 13 16:44"}, {"filename": "systemd-private-a30a5a178daa4042b42dfaf5ff9e5f68-chronyd.service-a1tpxv", "parent": ".", "flags": "drwx------.", "links": 3, "owner": "root", "group": "root", "size": 17, "date": "Feb 17 17:48"}, {"filename": "systemd-private-af69d7360f3e40cfa947358c0fb5a6f8-chronyd.service-T3MQ4j", "parent": ".", "flags": "drwx------.", "links": 3, "owner": "root", "group": "root", "size": 17, "date": "Feb 20 14:41"}, {"filename": "tmp.CvALl2jE6u", "parent": ".", "flags": "drwx------.", "links": 2, "owner": "root", "group": "root", "size": 6, "date": "Feb 13 16:44"}, {"filename": "tmp.e7AlxSxY5a", "parent": ".", "flags": "drwx------.", "links": 2, "owner": "root", "group": "root", "size": 6, "date": "Feb 20 14:41"}, {"filename": "tmp.uXm9yegjwj", "parent": ".", "flags": "drwx------.", "links": 2, "owner": "root", "group": "root", "size": 6, "date": "Feb 17 17:48"}, {"filename": "a regular filename", "parent": "./lstest", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:12"}, {"filename": "\n\nthis file has\na combination\n\n\nof everything\n\n\n\n", "parent": "./lstest", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:17"}, {"filename": "this file has\na newline inside", "parent": "./lstest", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:14"}, {"filename": "this file has\n\n\n\nfour contiguous newlines inside", "parent": "./lstest", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:14"}, {"filename": "this file\nhas\nsix\n\nnewlines\n\nwithin", "parent": "./lstest", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:16"}, {"filename": "\n\n\n\nthis file starts with four newlines", "parent": "./lstest", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:40"}, {"filename": "\nthis file starts with one newline", "parent": "./lstest", "flags": "-rw-rw-r--.", "links": 1, "owner": "kbrazil", "group": "kbrazil", "size": 0, "date": "Feb 22 00:13"}]

View File

@@ -0,0 +1,45 @@
.:
total 4
drwxrwxr-x. 2 kbrazil kbrazil 4096 Feb 22 00:40 lstest
drwx------. 3 root root 17 Feb 13 16:44 systemd-private-016de60725a3426792b93fc9f120b8f0-chronyd.service-oZqq4u
drwx------. 3 root root 17 Feb 17 17:48 systemd-private-a30a5a178daa4042b42dfaf5ff9e5f68-chronyd.service-a1tpxv
drwx------. 3 root root 17 Feb 20 14:41 systemd-private-af69d7360f3e40cfa947358c0fb5a6f8-chronyd.service-T3MQ4j
drwx------. 2 root root 6 Feb 13 16:44 tmp.CvALl2jE6u
drwx------. 2 root root 6 Feb 20 14:41 tmp.e7AlxSxY5a
drwx------. 2 root root 6 Feb 17 17:48 tmp.uXm9yegjwj
./lstest:
total 0
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:12 a regular filename
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:17
this file has
a combination
of everything
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:14 this file has
a newline inside
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:14 this file has
four contiguous newlines inside
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:16 this file
has
six
newlines
within
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:40
this file starts with four newlines
-rw-rw-r--. 1 kbrazil kbrazil 0 Feb 22 00:13
this file starts with one newline

View File

@@ -0,0 +1 @@
[{"filename": "a regular filename"}, {"filename": "this file has"}, {"filename": "a combination"}, {"filename": "of everything"}, {"filename": "this file has"}, {"filename": "a newline inside"}, {"filename": "this file has"}, {"filename": "four contiguous newlines inside"}, {"filename": "this file"}, {"filename": "has"}, {"filename": "six"}, {"filename": "newlines"}, {"filename": "within"}, {"filename": "this file starts with four newlines"}, {"filename": "this file starts with one newline"}]

View File

@@ -0,0 +1,33 @@
a regular filename
this file has
a combination
of everything
this file has
a newline inside
this file has
four contiguous newlines inside
this file
has
six
newlines
within
this file starts with four newlines
this file starts with one newline

1
tests/fixtures/centos-7.7/ntpq-p.json vendored Normal file
View File

@@ -0,0 +1 @@
[{"state": null, "remote": "44.190.6.254", "refid": "127.67.113.92", "st": 2, "t": "u", "when": 1, "poll": 64, "reach": 1, "delay": 23.399, "offset": -2.805, "jitter": 2.131}, {"state": null, "remote": "ntp.wdc1.us.lea", "refid": "130.133.1.10", "st": 2, "t": "u", "when": null, "poll": 64, "reach": 1, "delay": 93.053, "offset": -0.807, "jitter": 2.839}, {"state": null, "remote": "clock.team-cymr", "refid": "204.9.54.119", "st": 2, "t": "u", "when": null, "poll": 64, "reach": 1, "delay": 70.337, "offset": -2.909, "jitter": 2.6}, {"state": null, "remote": "mirror1.sjc02.s", "refid": "216.218.254.202", "st": 2, "t": "u", "when": 2, "poll": 64, "reach": 1, "delay": 29.325, "offset": 1.044, "jitter": 4.069}]

6
tests/fixtures/centos-7.7/ntpq-p.out vendored Normal file
View File

@@ -0,0 +1,6 @@
remote refid st t when poll reach delay offset jitter
==============================================================================
44.190.6.254 127.67.113.92 2 u 1 64 1 23.399 -2.805 2.131
ntp.wdc1.us.lea 130.133.1.10 2 u - 64 1 93.053 -0.807 2.839
clock.team-cymr 204.9.54.119 2 u - 64 1 70.337 -2.909 2.600
mirror1.sjc02.s 216.218.254.202 2 u 2 64 1 29.325 1.044 4.069

View File

@@ -0,0 +1 @@
[{"state": "+", "remote": "44.190.6.254", "refid": "127.67.113.92", "st": 2, "t": "u", "when": 66, "poll": 64, "reach": 377, "delay": 22.69, "offset": -0.392, "jitter": 2.085}, {"state": "-", "remote": "108.59.2.24", "refid": "130.133.1.10", "st": 2, "t": "u", "when": 63, "poll": 64, "reach": 377, "delay": 90.805, "offset": 2.84, "jitter": 1.908}, {"state": "+", "remote": "38.229.71.1", "refid": "204.9.54.119", "st": 2, "t": "u", "when": 64, "poll": 64, "reach": 377, "delay": 68.699, "offset": -0.61, "jitter": 2.576}, {"state": "*", "remote": "72.5.72.15", "refid": "216.218.254.202", "st": 2, "t": "u", "when": 63, "poll": 64, "reach": 377, "delay": 22.654, "offset": 0.231, "jitter": 1.964}]

6
tests/fixtures/centos-7.7/ntpq-pn.out vendored Normal file
View File

@@ -0,0 +1,6 @@
remote refid st t when poll reach delay offset jitter
==============================================================================
+44.190.6.254 127.67.113.92 2 u 66 64 377 22.690 -0.392 2.085
-108.59.2.24 130.133.1.10 2 u 63 64 377 90.805 2.840 1.908
+38.229.71.1 204.9.54.119 2 u 64 64 377 68.699 -0.610 2.576
*72.5.72.15 216.218.254.202 2 u 63 64 377 22.654 0.231 1.964

1
tests/fixtures/centos-7.7/passwd.json vendored Normal file
View File

@@ -0,0 +1 @@
[{"username": "root", "password": "x", "uid": 0, "gid": 0, "comment": "root", "home": "/root", "shell": "/bin/bash"}, {"username": "bin", "password": "x", "uid": 1, "gid": 1, "comment": "bin", "home": "/bin", "shell": "/sbin/nologin"}, {"username": "daemon", "password": "x", "uid": 2, "gid": 2, "comment": "daemon", "home": "/sbin", "shell": "/sbin/nologin"}, {"username": "adm", "password": "x", "uid": 3, "gid": 4, "comment": "adm", "home": "/var/adm", "shell": "/sbin/nologin"}, {"username": "lp", "password": "x", "uid": 4, "gid": 7, "comment": "lp", "home": "/var/spool/lpd", "shell": "/sbin/nologin"}, {"username": "sync", "password": "x", "uid": 5, "gid": 0, "comment": "sync", "home": "/sbin", "shell": "/bin/sync"}, {"username": "shutdown", "password": "x", "uid": 6, "gid": 0, "comment": "shutdown", "home": "/sbin", "shell": "/sbin/shutdown"}, {"username": "halt", "password": "x", "uid": 7, "gid": 0, "comment": "halt", "home": "/sbin", "shell": "/sbin/halt"}, {"username": "mail", "password": "x", "uid": 8, "gid": 12, "comment": "mail", "home": "/var/spool/mail", "shell": "/sbin/nologin"}, {"username": "operator", "password": "x", "uid": 11, "gid": 0, "comment": "operator", "home": "/root", "shell": "/sbin/nologin"}, {"username": "games", "password": "x", "uid": 12, "gid": 100, "comment": "games", "home": "/usr/games", "shell": "/sbin/nologin"}, {"username": "ftp", "password": "x", "uid": 14, "gid": 50, "comment": "FTP User", "home": "/var/ftp", "shell": "/sbin/nologin"}, {"username": "nobody", "password": "x", "uid": 99, "gid": 99, "comment": "Nobody", "home": "/", "shell": "/sbin/nologin"}, {"username": "systemd-network", "password": "x", "uid": 192, "gid": 192, "comment": "systemd Network Management", "home": "/", "shell": "/sbin/nologin"}, {"username": "dbus", "password": "x", "uid": 81, "gid": 81, "comment": "System message bus", "home": "/", "shell": "/sbin/nologin"}, {"username": "polkitd", "password": "x", "uid": 999, "gid": 998, "comment": "User for polkitd", "home": "/", "shell": "/sbin/nologin"}, {"username": "sshd", "password": "x", "uid": 74, "gid": 74, "comment": "Privilege-separated SSH", "home": "/var/empty/sshd", "shell": "/sbin/nologin"}, {"username": "postfix", "password": "x", "uid": 89, "gid": 89, "comment": "", "home": "/var/spool/postfix", "shell": "/sbin/nologin"}, {"username": "chrony", "password": "x", "uid": 998, "gid": 996, "comment": "", "home": "/var/lib/chrony", "shell": "/sbin/nologin"}, {"username": "joeuser", "password": "x", "uid": 1000, "gid": 1000, "comment": "joeuser", "home": "/home/joeuser", "shell": "/bin/bash"}, {"username": "dockerroot", "password": "x", "uid": 997, "gid": 994, "comment": "Docker User", "home": "/var/lib/docker", "shell": "/sbin/nologin"}]

21
tests/fixtures/centos-7.7/passwd.out vendored Normal file
View File

@@ -0,0 +1,21 @@
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
polkitd:x:999:998:User for polkitd:/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
chrony:x:998:996::/var/lib/chrony:/sbin/nologin
joeuser:x:1000:1000:joeuser:/home/joeuser:/bin/bash
dockerroot:x:997:994:Docker User:/var/lib/docker:/sbin/nologin

1
tests/fixtures/centos-7.7/shadow.json vendored Normal file
View File

@@ -0,0 +1 @@
[{"username": "root", "password": "$6$27lBiByDWdiM7lvJ$ulWkJyfKNbqDnrIKPLhUCGanKcS5TdY3ZasKMR/v2dl0mHn0s28LcxTXMqqOV0d6tww0U4gmgYZezgAf/F8Pz.", "last_changed": null, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "bin", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "daemon", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "adm", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "lp", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "sync", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "shutdown", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "halt", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "mail", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "operator", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "games", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "ftp", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "nobody", "password": "*", "last_changed": 17834, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "systemd-network", "password": "!!", "last_changed": 18123, "minimum": null, "maximum": null, "warn": null, "inactive": null, "expire": null}, {"username": "dbus", "password": "!!", "last_changed": 18123, "minimum": null, "maximum": null, "warn": null, "inactive": null, "expire": null}, {"username": "polkitd", "password": "!!", "last_changed": 18123, "minimum": null, "maximum": null, "warn": null, "inactive": null, "expire": null}, {"username": "sshd", "password": "!!", "last_changed": 18123, "minimum": null, "maximum": null, "warn": null, "inactive": null, "expire": null}, {"username": "postfix", "password": "!!", "last_changed": 18123, "minimum": null, "maximum": null, "warn": null, "inactive": null, "expire": null}, {"username": "chrony", "password": "!!", "last_changed": 18123, "minimum": null, "maximum": null, "warn": null, "inactive": null, "expire": null}, {"username": "joeuser", "password": "$6$sR1OEFM1KVuMeBUt$NhanSmm91.BspCYlMtrjYhc71FElgaCP7uSUAwhtQVFGcYa7.8VPMmRce77yS8FLy6XSYBtcCeZCJhnLOicc/.", "last_changed": null, "minimum": 0, "maximum": 99999, "warn": 7, "inactive": null, "expire": null}, {"username": "dockerroot", "password": "!!", "last_changed": 18123, "minimum": null, "maximum": null, "warn": null, "inactive": null, "expire": null}]

Some files were not shown because too many files have changed in this diff Show More