2012-05-08 70 views
1

我有一個python腳本,想ping幾個(相當於幾個!)主機。我已經將它設置爲讀取hosts.txt文件的內容作爲主機在腳本中進行ping操作。奇怪的是,我recieving下面的錯誤,在最初的幾個地址(無論它們是什麼):Python腳本中的ping請求失敗

Ping request could not find host 66.211.181.182. Please check the name and try again. 

我已經包含如上圖所示,在兩次(在文件中)的地址,它會嘗試平。任何想法,我做錯了 - 我是一個蟒蛇新手,所以要溫柔。


這裏是我的腳本:

import subprocess 

hosts_file = open("hosts.txt","r") 
lines = hosts_file.readlines() 

for line in lines: 
    ping = subprocess.Popen(
     ["ping", "-n", "1",line], 
     stdout = subprocess.PIPE, 
     stderr = subprocess.PIPE 
    ) 
    out, error = ping.communicate() 
    print out 
    print error 
hosts_file.close() 

這裏是我的HOSTS.TXT文件:

66.211.181.182 
178.236.5.39 
173.194.67.94 
66.211.181.182 

這裏是從上面的測試結果:

Ping request could not find host 66.211.181.182 
. Please check the name and try again. 


Ping request could not find host 178.236.5.39 
. Please check the name and try again. 


Ping request could not find host 173.194.67.94 
. Please check the name and try again. 



Pinging 66.211.181.182 with 32 bytes of data: 
Request timed out. 

Ping statistics for 66.211.181.182: 
    Packets: Sent = 1, Received = 0, Lost = 1 (100% loss) 
+0

@EliAcherkan,這是有道理的,我想.. 。當我測試這個閱讀部分時,我只是簡單地打印了這些線條,它打破了線條。我將如何克服這一點? – MHibbin

+0

感謝那 – MHibbin

回答

2

看起來像line變量在結尾處包含換行符(文件的最後一行除外)。從Python tutorial

f.readline()從文件讀取一行;一個換行符(\n)留在字符串的末尾,並且只在文件的最後一行中省略,如果該文件不以換行符結束。

你需要調用Popen之前剝離\nHow can I remove (chomp) a newline in Python?

+1

這就是門票! - 我添加了「line = line.strip()」來從兩側去掉所有的空白空間,而不僅僅是一個新行。感謝您的幫助:) – MHibbin

+0

不客氣! –

1

幾點意見:

  1. 使用readlines方法()強烈不推薦,因爲它會在整個文件加載到內存中。
  2. 我建議使用發生器爲了在每一行執行rstrip然後ping服務器。
  3. 無需file.close使用 - 你可以用它做你

您的代碼語句中使用應該是這樣的:

import subprocess 
def PingHostName(hostname): 
    ping=subprocess.Popen(["ping","-n","1",hostname],stdout=subprocess.PIPE 
        ,stderr=subprocess.PIPE) 
    out,err=ping.communicate(); 
    print out 
    if err is not None: print err 

with open('C:\\myfile.txt') as f: 
    striped_lines=(line.rstrip() for line in f) 
    for x in striped_lines: PingHostName(x) 
+0

感謝您的反饋...幾個問題... 什麼是發電機...你使用它? – MHibbin

+0

生成器是通過惰性評估即時生成的對象。 當你使用生成器來檢查列表時,你並沒有真正創建列表並迭代它,每個項目都是在動態創建的。 你可以在http://wiki.python.org/moin/Generators 閱讀更多關於它們的信息,是的我在這裏使用生成器 (line.rstrip()for line for line)返回一個生成器對象 – asafm

+0

感謝響應...我看過發帖子中提到過的發電機,但並沒有真正理解我讀過的描述。您提供的描述非常有幫助。我會嘗試一下這個代碼,看看在週末使用生成器。謝謝 P.S.我會upvote你的答案,但沒有足夠的聲譽(或任何它被稱爲) – MHibbin