其他问题并不完全相同。
我正在实现的是一个Python函数,它返回系统上所有IP地址的列表,模仿以下行为:
ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | cut -d: -f2 | awk '{ print $1}'
答案 0 :(得分:5)
您可以使用subprocess
python模块来实现此目的。
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")
那应该会给你一个IP地址列表。
PS:最好使用以下命令
ifconfig | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2}' | cut -d\: -f2 | cut -d\ -f1
如果有的话,这将排除IPV6地址。
Pure Python Way
如果您希望在Python中完全执行此操作,请检查netifaces python模块。