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

后端 未结 8 1662
礼貌的吻别
礼貌的吻别 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:42

    You can get it like this (Tested with python 2.7 and Mac OS X Capitain but should work on GNU/Linux too): import subprocess

    def system_call(command):
        p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
        return p.stdout.read()
    
    
    def get_gateway_address():
        return system_call("route -n get default | grep 'gateway' | awk '{print $2}'")
    
    print get_gateway_address()
    

提交回复
热议问题