From 14cfdbe3ad42eeeddacac19b653321c55081851a Mon Sep 17 00:00:00 2001 From: ray-1337 <33544674+ray-1337@users.noreply.github.com> Date: Mon, 11 Apr 2022 22:24:49 +0200 Subject: [PATCH] added status list --- src/methods/status.js | 47 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/methods/status.js diff --git a/src/methods/status.js b/src/methods/status.js new file mode 100644 index 0000000..816d9c9 --- /dev/null +++ b/src/methods/status.js @@ -0,0 +1,47 @@ +const {exec} = require("child_process"); +const {promisify} = require("util"); +const promisifiedExec = promisify(exec); + +module.exports = function(raw) { + if (raw && typeof raw !== "boolean") { + throw new Error("The raw must be type of boolean."); + }; + + try { + let res = await promisifiedExec(`sudo ufw status`); + + if (res.stderr) throw new Error(res.stderr); + + if (res.stdout) { + if (!raw) { + let list = []; + + // parsing + let parsedStatus = res.stdout.replace(/\r|\n/gi, " ").split(/\s{2,}/gi).filter(x => x.length); + if (!parsedStatus.length) return []; + + let findAfterFrom = parsedStatus.findIndex(x => x == "----"); + if (!findAfterFrom.length) return []; + + let afterSlice = parsedStatus.slice(findAfterFrom + 1, parsedStatus.length); + if (!afterSlice.length) return []; + + for (let i = 0; i < afterSlice.length; i++) { + if (i % 3 == 0) { + let to = afterSlice[i]; + let action = afterSlice[i + 1]; + let from = afterSlice[i + 2]; + + list.push({to, action, from}); + }; + }; + + return list; + } else { + return res.stdout; + }; + }; + } catch (err) { + throw new Error(err); + }; +}; \ No newline at end of file