xref: /freebsd/tests/atf_python/sys/net/tools.py (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1#!/usr/local/bin/python3
2import json
3import os
4import socket
5import time
6from ctypes import cdll
7from ctypes import get_errno
8from ctypes.util import find_library
9from typing import List
10from typing import Optional
11
12
13class ToolsHelper(object):
14    NETSTAT_PATH = "/usr/bin/netstat"
15
16    @classmethod
17    def get_output(cls, cmd: str, verbose=False) -> str:
18        if verbose:
19            print("run: '{}'".format(cmd))
20        return os.popen(cmd).read()
21
22    @classmethod
23    def get_routes(cls, family: str, fibnum: int = 0):
24        family_key = {"inet": "-4", "inet6": "-6"}.get(family)
25        out = cls.get_output(
26            "{} {} -rn -F {} --libxo json".format(cls.NETSTAT_PATH, family_key, fibnum)
27        )
28        js = json.loads(out)
29        js = js["statistics"]["route-information"]["route-table"]["rt-family"]
30        if js:
31            return js[0]["rt-entry"]
32        else:
33            return []
34