Initial commit of AthonetTools
This commit is contained in:
42
services/local_net.py
Normal file
42
services/local_net.py
Normal file
@@ -0,0 +1,42 @@
|
||||
# services/local_net.py
|
||||
import subprocess
|
||||
import re
|
||||
|
||||
def _sh(cmd):
|
||||
out = subprocess.check_output(cmd, text=True)
|
||||
return out
|
||||
|
||||
def get_eth0_dhcp_snapshot():
|
||||
"""
|
||||
Returns {'iface':'eth0','cidr':'X.X.X.X/YY','ip':'X.X.X.X','prefixlen':YY,'gw':'A.B.C.D'}
|
||||
Raises on failure.
|
||||
"""
|
||||
iface = "eth0"
|
||||
|
||||
# ip -o -4 addr show dev eth0 | awk '{print $4}'
|
||||
addrs = _sh(["/sbin/ip", "-o", "-4", "addr", "show", "dev", iface]).strip()
|
||||
if not addrs:
|
||||
addrs = _sh(["ip", "-o", "-4", "addr", "show", "dev", iface]).strip()
|
||||
|
||||
m = re.search(r"\s(\d+\.\d+\.\d+\.\d+/\d+)\s", addrs)
|
||||
if not m:
|
||||
raise RuntimeError(f"No IPv4 address on {iface}")
|
||||
cidr = m.group(1)
|
||||
ip = cidr.split("/")[0]
|
||||
prefixlen = int(cidr.split("/")[1])
|
||||
|
||||
# ip route show default dev eth0 | awk '/default/ {print $3}'
|
||||
routes = _sh(["/sbin/ip", "route", "show", "default", "dev", iface])
|
||||
if not routes:
|
||||
routes = _sh(["ip", "route", "show", "default", "dev", iface])
|
||||
|
||||
m2 = re.search(r"default via (\d+\.\d+\.\d+\.\d+)", routes)
|
||||
gw = m2.group(1) if m2 else ""
|
||||
|
||||
return {
|
||||
"iface": iface,
|
||||
"cidr": cidr,
|
||||
"ip": ip,
|
||||
"prefixlen": prefixlen,
|
||||
"gw": gw
|
||||
}
|
||||
Reference in New Issue
Block a user