This commit is contained in:
@@ -228,28 +228,40 @@ _handle_re = re.compile(r"\s+#\s*handle\s+\d+\s*$")
|
||||
def extract_rule_lines_from_chain_text(text: str) -> List[str]:
|
||||
"""
|
||||
Given output of `nft list chain fam table chain`, extract the rule lines as strings.
|
||||
Keeps the rule text as printed by nft (one rule per line), strips leading/trailing whitespace,
|
||||
and removes trailing '# handle N' fragments.
|
||||
- Only consider indented lines (rules are indented inside the chain block).
|
||||
- Skip chain header metadata lines that typically end with ';' (e.g. "type ...; policy ...;").
|
||||
- Skip closing brace lines ('}').
|
||||
- Remove trailing '# handle N' fragments.
|
||||
Returns cleaned rule strings like "ip protocol icmp drop".
|
||||
"""
|
||||
lines: List[str] = []
|
||||
if not text:
|
||||
return lines
|
||||
|
||||
for raw in text.splitlines():
|
||||
line = raw.rstrip()
|
||||
# skip chain/table header lines which typically start with "table " or "chain "
|
||||
if line.strip() == "":
|
||||
# preserve the original raw to check indentation
|
||||
if raw is None:
|
||||
continue
|
||||
if line.lstrip().startswith("table "):
|
||||
# ignore empty lines
|
||||
if raw.strip() == "":
|
||||
continue
|
||||
if line.lstrip().startswith("chain "):
|
||||
# ignore closing braces (possibly with indentation)
|
||||
if raw.strip() == "}":
|
||||
continue
|
||||
# Only accept lines that are indented (start with whitespace).
|
||||
# This filters out top-level "table ..." and "chain ..." header lines.
|
||||
if not raw.startswith((" ", "\t")):
|
||||
# not indented => likely header/footer, skip
|
||||
continue
|
||||
# Now we have an indented line. Remove leading whitespace to get the content.
|
||||
line = raw.lstrip().rstrip()
|
||||
# skip chain metadata lines that end with ';' (e.g. "type filter hook ...; policy accept;")
|
||||
if line.endswith(";"):
|
||||
continue
|
||||
# rule lines are indented (start with whitespace). Accept them if non-empty after stripping.
|
||||
# Remove leading indentation:
|
||||
stripped = line.lstrip()
|
||||
# remove trailing " # handle N" if present
|
||||
stripped = _handle_re.sub("", stripped)
|
||||
if stripped:
|
||||
lines.append(stripped)
|
||||
line = _handle_re.sub("", line).rstrip()
|
||||
if line:
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user