获取主机的所有外部IP地址

Ror*_*ory 1 python networking ip-address

其他问题并不完全相同.

我正在实现的是一个Python函数,它返回系统上所有IP地址的列表,模拟以下行为:

ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | cut -d: -f2 | awk '{ print $1}'
Run Code Online (Sandbox Code Playgroud)

Kul*_*ini 5

您可以使用subprocesspython模块来实现此目的.

import subprocess
cmd = "ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | cut -d: -f2 | awk '{ print $1}'"
co = subprocess.Popen([cmd], shell = True, stdout = subprocess.PIPE)
ips = co.stdout.read().strip().split("\n")
Run Code Online (Sandbox Code Playgroud)

这应该给你一个IP地址列表.

PS:最好使用以下命令

ifconfig | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2}' | cut -d\: -f2 | cut -d\  -f1
Run Code Online (Sandbox Code Playgroud)

如果有的话,这将排除IPV6地址.

纯Python方式

如果你想在Python中完全这样做,那么请检查netifaces python模块.