2015-06-20 28 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我已經編輯我的答案,檢查出來 –

相關問題