Python:在linux中获取本地接口/ip地址的默认网关

Python:在linux中获取本地接口/ip地址的默认网关,python,linux,routing,networking,Python,Linux,Routing,Networking,在Linux上,如何使用python找到本地ip地址/接口的默认网关 我看到了“如何为UPnP获取内部IP、外部IP和默认网关”的问题,但公认的解决方案只显示了如何在windows上获取网络接口的本地IP地址 谢谢。它似乎可以做到这一点,但我还没有对它进行测试。对于那些不需要额外依赖项并且不喜欢调用子流程的人,以下是您自己通过直接阅读/proc/net/route来做到这一点的方法: def get_ip(): file=os.popen("ifconfig | grep 'addr:'

在Linux上,如何使用python找到本地ip地址/接口的默认网关

我看到了“如何为UPnP获取内部IP、外部IP和默认网关”的问题,但公认的解决方案只显示了如何在windows上获取网络接口的本地IP地址


谢谢。

它似乎可以做到这一点,但我还没有对它进行测试。

对于那些不需要额外依赖项并且不喜欢调用子流程的人,以下是您自己通过直接阅读
/proc/net/route
来做到这一点的方法:

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
import socket, struct

def get_default_gateway_linux():
    """Read the default gateway directly from /proc."""
    with open("/proc/net/route") as fh:
        for line in fh:
            fields = line.strip().split()
            if fields[1] != '00000000' or not int(fields[3], 16) & 2:
                # If not default route or not RTF_GATEWAY, skip it
                continue

            return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
导入套接字,结构
def get_default_gateway_linux():
“”“直接从/proc读取默认网关。”“”
开放(“/proc/net/route”)作为fh:
对于fh中的线路:
字段=line.strip().split()
如果字段[1]!='00000000'或非整型(字段[3],16)和2:
#如果不是默认路由或不是RTF_网关,请跳过它
持续
return socket.inet\u ntoa(struct.pack(“的最新版本也可以这样做,但与
pynetinfo
不同,它将在Linux以外的系统上工作(包括Windows、OS X、FreeBSD和Solaris)。

为了完整性(并扩展alastair的答案),下面是一个使用“netifaces”的示例(在Ubuntu10.04下测试,但应该是可移植的):

“netifaces”的文档:

您可以这样获得它(使用python 2.7和Mac OS X Capitain进行测试,但也应该在GNU/Linux上工作): 导入子流程

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()

下面是我使用python获取Mac和Linux默认网关的解决方案:

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)
对于Mac:

import subprocess

def get_default_gateway():
    route_default_result = str(subprocess.check_output(["route", "get", "default"]))
    start = 'gateway: '
    end = '\\n'
    if 'gateway' in route_default_result:
        return (route_default_result.split(start))[1].split(end)[0]

print(get_default_gateway())

您可以使用python执行系统的“route”命令,然后处理输出以获得默认网关。可能还有一个route标志仅用于打印。我不知道python的atm方式。祝您好运。该库很棒!它有一个netinfo.get\u routes方法,返回一个字典元组,其中正好包含我需要的数据。谢谢!如果您分别使用python 3或python 2,请在Debian/Ubuntu上通过
apt get install python3 netifaces
apt get install python netifaces
安装。
import subprocess

def get_default_gateway():
    route_default_result = str(subprocess.check_output(["route", "get", "default"]))
    start = 'gateway: '
    end = '\\n'
    if 'gateway' in route_default_result:
        return (route_default_result.split(start))[1].split(end)[0]

print(get_default_gateway())