2015-06-20 21 views
-1

嗨我想使用这个程序中的整数的ipaddress。但我需要在response = os.system("ping -c 1 " + hostname + "-I" + str(mystring))整数到相同的Python程序中的字符串转换

#!/usr/bin/python 
import os 
interface = os.system("ifconfig ge1 | grep UP") 
ip = os.system("ifconfig ge1.1 | grep UP") 
ipaddress = os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'") 
print ipaddress 
mystring = repr(ipaddress) 

print mystring 

if interface == 0: 
print interface, ' interface is UP!' 
hostname = "8.8.8.8" 
response = os.system("ping -c 1 " + hostname + "-I" + str(mystring)) 
if response == 0: 
    print hostname, 'is up!' 
else: 
    print hostname, 'is down!' 
else: 
    print interface, ' interface is down!' 
+1

进口ip地址类 – stark

+0

使用os.system()返回退出状态代码,而不是一个IP地址! –

+1

http://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-of-eth0-in-python/24196955#24196955 – stark

回答

0

os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'")将不会返回到你的IP地址,而不是退出状态代码来调用这个字符串,所以你需要使用一个模块,让你的接口的IP地址了(eth0 ,WLAN0..etc)

作为由@stark链路评论建议的,使用netifaces packagesocket 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() 
+0

谢谢Khalil。从上面的代码。我能够找到IP地址,但我如何可以建立该值作为输入的命令ping 8.8.8.8 -I get_ip_address('eth0') – user1056087

+0

@ user1056087我已经编辑我的答案,检查出来 –

相关问题