2016-07-04 16 views
1

當我使用創建簡單的Windows我嘗試執行ping IP地址時,創建一個簡單的if聲明如果在Python聲明束縛IP地址

import os 
hostname = "192.168.8.8." #example 
response = os.system("ping -c 1 " + hostname) 

#and then check the response... 
if response == 0: 
    print hostname, 'is down' 

else: 
    print hostname, 'is up' 

print response 

我在此很新,但沒有不管我輸入的IP地址是否有效,它都表示它已經啓動。

回答

1

os.system()返回進程退出值。 0表示成功。

在你的情況下,它正在成功執行,因此它返回0.你所要做的就是從ping命令中獲得完整的輸出,然後進行字符串比較以確定該IP是否活着。

您需要使用subprocess's checkoutput method

import subprocess 

hostname = "google.com" 
batcmd="ping -n 1 " + hostname 
result = subprocess.check_output(batcmd, shell=True) 
if "Received = 1" in result: 
    print "Is UP" 
else: 
    print "Is Down" 
0

使用我的回答here取出接口參數subprocess.check_call的變化:

from subprocess import check_call, CalledProcessError, PIPE 

def is_reachable(i, add): 
    command = ["ping", "-c", i, add] 
    try: 
     check_call(command,sdout=PIPE) 
     return True 
    except CalledProcessError as e: 
     return False 

if is_reachable("3", "127.0.0.01"): 
# host is reachable 
else: 
    # not reachable 

在Windows下你可能需要添加ARGS "-w", "2999"得到其他的東西對於無法訪問的主機,返回錯誤級別爲0,因爲即使對於不成功的調用,返回碼也將爲零,windows-7-get-no-reply-but-sets-errorlevel-to-0

你也可以使用check_output,特別是檢查是否Destination host unreachable是輸出:

return "Destination host unreachable" in check_output(command) 
0

你做的一切都是好的,唯一的問題是,你糊塗了正確的輸出是0與錯誤的輸出,這是一切以上0.

import os 
hostname = "192.168.8.8." #example 
response = os.system("ping -c 1 " + hostname) 

#and then check the response... 
if response == 0: 
    print hostname, 'is up' 

else: 
    print hostname, 'is down' 

print response 
+0

如果這是真的,它總是會說起來嗎? –

+0

也許他輸入的IP始終是錯誤的或無效的。你可以檢查代碼,如果你想。您的迴應建議另一個功能不處理OP問題。 –

+0

*但不管我輸入的IP地址是否有效,它說明它是*應該是非常自我解釋的,它在兩個方向上都不會出錯 –