2017-04-10 69 views
-1

我有,我想自動執行以下程序,分配IP地址遵循這些準則某些系統的特定池: 1.跳過前10級的IP 2.填充IP地址每個子網- Python腳本跳過行

我使用Python 3.5.1 我可是從CSV文件工作,這裏是一個數據我一起工作的樣品:

  • 網絡堆棧等系統單位
  • 10.0.28.0 CAB_DS4-2_2
  • 10.0.28.32 CAB_DS4-2_2
  • 10.0.28.64 CAB_DS4-1_1
  • 10.0.28.96 CAB_DS4-1_2
  • 10.0.28.128 CAB_DS3-2_1
  • 10.0.28.160 CAB_DS3-3_1
  • 10.0.28.192 CAB_DS3 -3_2
  • 10.0.28.224 CAB_DS2-2_1

這裏是我做的代碼,它適用於數據正好一半,從8個子網,它只有4個分配的。下面是代碼:

import csv 
import ipaddress 

with open('sorted2.csv') as csv_file: 
    ip_pool = csv.reader(csv_file) 
    next(ip_pool) 

    for row in ip_pool: 
     ip = ipaddress.ip_address(row[0]) 
     nextROW = next(ip_pool) 
     ip_end = nextROW[0] #NEXT network limit 
     counter = 0 

     ip_end = ipaddress.ip_address(ip_end) 
     ip_next = ip + 9 # skip first 10 IPs 
     ip_assign = ipaddress.ip_address(ip_next) 

     print ('NEW NET:', ip) 
     while ipaddress.ip_address(ip_assign) < ipaddress.ip_address(ip_end)-1: 
      counter += 1 # count number of IPs assigned, to be implemented later 
      ip_assign = ipaddress.ip_address(ip_assign)+1 #iterate next IP 
      ip_start = ip_assign 

      print(ip_assign) 
     ip_next = ip_assign 

這裏是代碼的輸出:

NEW NET: 10.0.28.0 
10.0.28.10 
10.0.28.11 
10.0.28.12 
10.0.28.13 
10.0.28.14 
10.0.28.15 
10.0.28.16 
10.0.28.17 
10.0.28.18 
10.0.28.19 
10.0.28.20 
10.0.28.21 
10.0.28.22 
10.0.28.23 
10.0.28.24 
10.0.28.25 
10.0.28.26 
10.0.28.27 
10.0.28.28 
10.0.28.29 
10.0.28.30 
10.0.28.31 
NEW NET: 10.0.28.64 
10.0.28.74 
10.0.28.75 
10.0.28.76 
10.0.28.77 
10.0.28.78 
10.0.28.79 
10.0.28.80 
10.0.28.81 
10.0.28.82 
10.0.28.83 
10.0.28.84 
10.0.28.85 
10.0.28.86 
10.0.28.87 
10.0.28.88 
10.0.28.89 
10.0.28.90 
10.0.28.91 
10.0.28.92 
10.0.28.93 
10.0.28.94 
10.0.28.95 
NEW NET: 10.0.28.128 
10.0.28.138 
10.0.28.139 
10.0.28.140 
10.0.28.141 
10.0.28.142 
10.0.28.143 
10.0.28.144 
10.0.28.145 
10.0.28.146 
10.0.28.147 
10.0.28.148 
10.0.28.149 
10.0.28.150 
10.0.28.151 
10.0.28.152 
10.0.28.153 
10.0.28.154 
10.0.28.155 
10.0.28.156 
10.0.28.157 
10.0.28.158 
10.0.28.159 
NEW NET: 10.0.28.192 
10.0.28.202 
10.0.28.203 
10.0.28.204 
10.0.28.205 
10.0.28.206 
10.0.28.207 
10.0.28.208 
10.0.28.209 
10.0.28.210 
10.0.28.211 
10.0.28.212 
10.0.28.213 
10.0.28.214 
10.0.28.215 
10.0.28.216 
10.0.28.217 
10.0.28.218 
10.0.28.219 
10.0.28.220 
10.0.28.221 
10.0.28.222 
10.0.28.223 

正如你所看到的,它跳過子網4,我似乎無法把我的手指上有什麼我編碼錯誤/忘記了。任何幫助非常感謝

+1

通過調用'next(ip_pool)'來修改'ip_pool'' –

回答

0

在迭代它時,您不應該修改ip_pool

相反迭代行並試圖獲得,而迭代接下來,跟蹤上一行的(我們仍然可以將其命名row)的,但是我們的迭代將取代當前排過的下一行,:

row = next(ip_pool) 
for nextROW in ip_pool: 
    ... 
    row = nextROW 
+0

好吧我理解你的意思只是不知道如何實現你在我的代碼暗示的修復程序 – user7421969

+0

我不是當然還有什麼可以解釋的。在循環開始時,將其替換爲我發佈的循環開始。在循環結尾添加'row = nextROW'行。 '...'應該保持不變,儘管你應該刪除'nextROW = next(ip_pool)'這一行,因爲'nextROW'的值已經被處理了。 –

+0

非常感謝。 – user7421969