在Linux中,Python:获取本地接口/IP地址的默认网关。

19

在Linux系统中,我如何使用Python查找本地IP地址/接口的默认网关?

我看到了一个问题“如何获取UPnP的内部IP、外部IP和默认网关”,但是被接受的解决方案只展示了如何获取Windows系统上网络接口的本地IP地址。

谢谢。


你可以使用Python执行系统的“route”命令,然后处理输出以获取默认网关。可能还有一个标志可以让路由器仅打印那个。我目前不知道Python的方法。祝好运。 - user132014
9个回答

36

对于那些不想要额外依赖且不喜欢调用子进程的人,这里是如何通过直接读取/proc/net/route来自己完成它:

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

我没有一台大端模式的机器进行测试,所以我不确定字节顺序是否取决于处理器架构,但如果取决于处理器架构,请将 struct.pack('<L', ... 中的<替换为=,这样代码就会使用本地的字节顺序。


只有在您有一个默认网关的情况下才有效。如果您有多个网关,则使用最低度量值的那个。 - delijati

20

为了完整性(并且扩展alastair的答案),这里提供一个使用"netifaces"的示例(在Ubuntu 10.04下测试,但这应该是可移植的):

$ sudo easy_install netifaces
Python 2.6.5 (r265:79063, Oct  1 2012, 22:04:36)
...
$ ipython
...
In [8]: import netifaces
In [9]: gws=netifaces.gateways()
In [10]: gws
Out[10]:
{2: [('192.168.0.254', 'eth0', True)],
 'default': {2: ('192.168.0.254', 'eth0')}}
In [11]: gws['default'][netifaces.AF_INET][0]
Out[11]: '192.168.0.254'

'netifaces' 文档:https://pypi.python.org/pypi/netifaces/


在Debian/Ubuntu上,如果你使用Python 3或Python 2,可以通过apt-get install python3-netifacesapt-get install python-netifaces进行安装。 - famzah

6

1
那个库非常好!它有一个 netinfo.get_routes 方法,返回一个包含我所需数据的字典元组。谢谢! - GnP

3
最新版本的 netifaces 也可以实现这一功能,但与 pynetinfo 不同的是,它可以在除 Linux 外的其他系统上运行(包括 Windows、OS X、FreeBSD 和 Solaris)。

1
如果您有多个默认网关,以下是解决方案。
import socket, struct
from pprint import pprint as pp

with open("/proc/net/route") as fh:
    # skip header
    next(fh)
    route_list = []
    for line in fh:
        routes = line.strip().split()
        destination = socket.inet_ntoa(struct.pack("<L", int(routes[1], 16)))
        if destination != "0.0.0.0":
            continue
        gateway = socket.inet_ntoa(struct.pack("<L", int(routes[2], 16)))
        mask = socket.inet_ntoa(struct.pack("<L", int(routes[7], 16)))
        metric = routes[6]
        interface = routes[0]
        route_table = (destination, gateway, mask, metric, interface)
        route_list.append(route_table)
    pp(route_list)

#[('0.0.0.0', '0.0.0.0', '0.0.0.0', '0', 'wlan0'),
# ('0.0.0.0', '192.168.225.1', '0.0.0.0', '1024', 'usb0')]


1
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

1

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

0
你可以像这样获取它(在Python 2.7和Mac OS X Capitain上测试过,但在GNU / Linux上也应该可以工作): 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()

在Ubuntu 20.04上,将系统调用替换为route | grep default | sed -r 's/\s+/ /g' | cut -f 2 -d ' ' - dzmanto

0

这是我使用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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接