Python: get default gateway for a local interface/ip address in linux

后端 未结 8 1576
礼貌的吻别
礼貌的吻别 2020-12-06 01:09

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

相关标签:
8条回答
  • 2020-12-06 01:50

    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)
    
    0 讨论(0)
  • 2020-12-06 01:53
    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
    
    0 讨论(0)
提交回复
热议问题