2016-06-12 67 views
0

好的,我希望能夠輸入開始和結束的IP,並且ping它們之間的所有IP地址,包括列出的IP地址,然後將它們的結果顯示到.txt文檔中。我可以讓它爲單個IP工作,但我不知道如何製作,因此用戶必須輸入2個IP,並且它能夠成功地ping通所有的IP。謝謝。這是目前我所擁有的,但有麻煩。IP pinging的範圍

def pingNetwork(): 


startingIP = raw_input("Enter starting IP address: ") 
response = os.system("ping -c 1 " + startingIP) 
for ip in range(1, 100): 

if response == 0: 
    with open('IP_LOG_TIMESTAMP.txt', 'w') as f: 
     f.write(startingIP + ' is up!') 
else: 
    with open('IP_LOG_TIMESTAMP.txt', 'w') as f: 
     f.write(startingIP + ' is down!') 

回答

0
import struct 
import socket 

def findIPs(start, end): 
    ipstruct = struct.Struct('>I') 
    start, = ipstruct.unpack(socket.inet_aton(start)) 
    end, = ipstruct.unpack(socket.inet_aton(end)) 
    return [socket.inet_ntoa(ipstruct.pack(i)) for i in range(start, end+1)] 

def pingNetwork(range_ips): 
    for ip in range_ips: 
     response = os.system("ping -c 1 " + ip) 
     if response == 0: 
      with open('IP_LOG_TIMESTAMP.txt', 'w') as f: 
       f.write(ip+ ' is up!') 
     else: 
      with open('IP_LOG_TIMESTAMP.txt', 'w') as f: 
       f.write(ip+ ' is down!') 

ips = findIPs('111.111.111.0', '111.111.111.3') 
pingNetwork(ips)