From 51875eb9b7f8e33754b8aac353e6322a84eac546 Mon Sep 17 00:00:00 2001 From: KOLANICH Date: Tue, 31 May 2022 12:49:00 +0300 Subject: [PATCH] Improved getting interface and network by making it more correct and getting rid of sed scripting. --- aioarping/__main__.py | 15 +++++---------- aioarping/utils.py | 39 +++++++++++++++++++++++++++++++++++++++ setup.py | 6 +++++- 3 files changed, 49 insertions(+), 11 deletions(-) create mode 100644 aioarping/utils.py diff --git a/aioarping/__main__.py b/aioarping/__main__.py index 366628b..e9609aa 100644 --- a/aioarping/__main__.py +++ b/aioarping/__main__.py @@ -23,7 +23,10 @@ # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR # IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE -import subprocess, asyncio, aioarping, ipaddress +import asyncio, aioarping, ipaddress + + +from .utils import get_interface_and_network def my_process(data): @@ -33,15 +36,7 @@ def my_process(data): event_loop = asyncio.get_event_loop() -mydomain = [ - x - for x in subprocess.getoutput( - "ip route|sed '/via/d' |sed '/docker/d'|sed '/linkdown/d'|sed '/src /!d' | sed '/dev /!d' |sed '2,$d'" - ).split(" ") - if x -] -myiface = mydomain[2] -mydomain = mydomain[0] +myiface, mydomain = get_interface_and_network() # First create and configure a raw socket mysocket = aioarping.create_raw_socket(myiface) diff --git a/aioarping/utils.py b/aioarping/utils.py new file mode 100644 index 0000000..46939e6 --- /dev/null +++ b/aioarping/utils.py @@ -0,0 +1,39 @@ +def prefilter_route_lines(lines): + """https://github.com/brandonmpace/routeparser/issues/2""" + + for el in lines: + if "linkdown" in el: + continue + if "src" not in el: + continue + yield el + + +def post_filter_routes(routes): + for r in routes: + if "docker" in r.interface: + continue + if r.gateway is not None: + continue + yield r + + +def get_ip_route_lines(): + import subprocess + + return subprocess.getoutput("/usr/sbin/ip route").splitlines() + + +def get_needed_routes(): + import routeparser + + routeLines = list(prefilter_route_lines(get_ip_route_lines())) + t = routeparser.RoutingTable.from_ip_route_lines(routeLines) + return post_filter_routes(t.routes) + + +def get_interface_and_network(): + r = next(iter(get_needed_routes())) + ifc = r.interface + domain = r.network + return ifc, domain diff --git a/setup.py b/setup.py index a616919..b412f7d 100644 --- a/setup.py +++ b/setup.py @@ -13,7 +13,11 @@ download_url="http://github.com/frawau/aiolifx/archive/aioarping/0.1.3.tar.gz", keywords=["arp", "mac address", "presence", "automation"], license="MIT", - install_requires=["ipaddress",], + install_requires=["ipaddress"], + extras_require = { + "utils": ["routeparser"], + "cli": ["aioarping[utils]"], + }, # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "License :: OSI Approved :: MIT License",