os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'")
将不会返回到你的IP地址,而不是退出状态代码来调用这个字符串,所以你需要使用一个模块,让你的接口的IP地址了(eth0 ,WLAN0..etc)
作为由@stark链路评论建议的,使用netifaces package或socket module,从this post采取例子:
import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[2][0]['addr']
print ip
================================================= ==========================
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
get_ip_address('eth0')
编辑-1:
建议你运行你的终端命令通过subprocess而不是os.system,因为我读过它更安全。
现在,如果你婉的IP_ADDRESS结果传递到您的ping
命令,在这里我们去:
import subprocess
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
hostname = "8.8.8.8"
cmdping = "ping -c 1 " + hostname + " -I " + get_ip_address('eth0')
p = subprocess.Popen(cmdping, shell=True, stderr=subprocess.PIPE)
#The following while loop is meant to get you the output in real time, not to wait for the process to finish until then print the output.
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
进口ip地址类 – stark
使用os.system()返回退出状态代码,而不是一个IP地址! –
http://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-of-eth0-in-python/24196955#24196955 – stark