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