On Linux, how can I find the default gateway for a local ip address/interface using python?
I saw the question \"How to get internal IP, external IP and default gate
here my solution to get default gateway for Mac and Linux with python:
import subprocess
import re
import platform
def get_default_gateway_and_interface():
if platform.system() == "Darwin":
route_default_result = subprocess.check_output(["route", "get", "default"])
gateway = re.search(r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}", route_default_result).group(0)
default_interface = re.search(r"(?:interface:.)(.*)", route_default_result).group(1)
elif platform.system() == "Linux":
route_default_result = re.findall(r"([\w.][\w.]*'?\w?)", subprocess.check_output(["ip", "route"]))
gateway = route_default_result[2]
default_interface = route_default_result[4]
if route_default_result:
return(gateway, default_interface)
else:
print("(x) Could not read default routes.")
gateway, default_interface = get_default_gateway_and_interface()
print(gateway)
def get_ip():
file=os.popen("ifconfig | grep 'addr:'")
data=file.read()
file.close()
bits=data.strip().split('\n')
addresses=[]
for bit in bits:
if bit.strip().startswith("inet "):
other_bits=bit.replace(':', ' ').strip().split(' ')
for obit in other_bits:
if (obit.count('.')==3):
if not obit.startswith("127."):
addresses.append(obit)
break
return addresses